tags:

views:

136

answers:

1

I have two classes, one derived from the other and both have parametrized constructors. I want to call the constructor in both classes when I instantiate the derived class.

So my question is: what is the syntax to pass parameters to both base and derived classes from the calling code?

I tried something like this but it does not compile:

DerivedClass derivedclass = new DerivedClass(arguments):base( arguments);
+12  A: 

Unfortunately you cannot pass values to different constructors from the calling code. In other words this will not work:

Foo foo = new Foo(arg1):base(arg2)

What you can do however is set up the constructors in Foo to do this for you. Try something like this:

class FooBase
{
    public FooBase(Arg2 arg2)
    {
        // constructor stuff
    }
}

class Foo : FooBase
{
    public Foo(Arg1 arg1, Arg2 arg2)
        : base(arg2)
    {
        // constructor stuff
    }
}

Then you would invoke the constructor like this:

Foo foo = new Foo(arg1, arg2)

and the Foo constructor will route arg2 to the base constructor for you.

Andrew Hare