Search code examples
c#inheritancevisual-studio-2015abstract-classsubclassing

abstract inheritance in C#


I'm working on an assignment that will allow the user to purchase tickets for a few different types of events. I have to use a class for tickets that can't be instantiated, with a subclass for each of the specific types of ticket.

I've run in to my first snag, which is that the parameters on the base constructor for the subclass is giving me an error "An object reference is required for non-static field"

Here is the base class

abstract class Ticket
{
    public int ticketcount;
    public double ticketprice;

    public Ticket()
    {
        ticketcount = 0;
        ticketprice = 0;
    }

    public Ticket(int ticketcount, double ticketprice)
    {
        this.ticketcount = ticketcount;
        this.ticketprice = ticketprice;
    }

}

and here is the subclass.

class PlayTicket : Ticket
{
    public PlayTicket() : base()
    {

    }

    public PlayTicket(string sn) : base(ticketcount, ticketprice)
    {

    }
}

the error is occurring on the line

public PlayTicket(string sn) : base(ticketcount, ticketprice)

where the variables "ticketcount" and "ticketprice" are. How would I best be able to get around this? Or am I completely misunderstanding how and why to use a non-instatiatable class?


Solution

  • When you call parent constructor child constructor, you should pass argument value from child constructor to parent constructor.

    You child constructor should be like this :

    public PlayTicket(string sn, int ticketcount,double ticketprice) : base(ticketcount, ticketprice)
    {
    
    }
    

    This way, ticketcount and ticketprice goes to parent constructor and initialize accordingly.

    When creating new object of PlayTicket, you should do :

    Ticket playTicket = new PlayTicket("mySN", 20, 200);
    

    As JonSkeet suggested in the comment that you should use decimal for money value.