Tuesday, 10 September 2013

Can I pass arguments to a base constructor from a derived class's default constructor?

Can I pass arguments to a base constructor from a derived class's default
constructor?

Suppose I have an abstract base class Deck:
public abstract class Deck
{
public List<Card> cards;
public Deck(string[] values, string[] suits)
{...}
...
}
and a derived class EuchreDeck:
public class EuchreDeck : Deck
{
string[] values = new string[] { "9", "10", "J", "Q", "K", "A" };
string[] suits = new string[] { "clubs", "spades", "hearts", "diamonds" };
public EuchreDeck() : base(values, suits) // Error.
{}
...
}
I want the ability to instantiate EuchreDeck and have the two string
arrays passed to the base class, i.e. var gameDeck = new EuchreDeck();.
Currently I'm getting the error: "An object reference is required for the
non-static field, method, or property EuchreDeck.values."
Is this possible, or will calling the derived default constructor always
call the base default constructor?

No comments:

Post a Comment