Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly call parent constructors

Tags:

c#

I have a set of classes where my base has a constructor that takes a configuration object and handles transferring the values to its properties.

abstract class A { public A(ObjType MyObj){} } 
abstract class B : A {}
class C : A {}
class D : B {}
class E : B {}

Is it possible to implicitly call a non-default base constructor from child classes or would I need to explicitly implement the signature up the chain to do it via constructors?

abstract class A { public A(ObjType MyObj){} } 
abstract class B : A { public A(ObjType MyObj) : base(MyObj){} }
class C : A { public A(ObjType MyObj) : base(MyObj){} }
class D : B { public A(ObjType MyObj) : base(MyObj){} }
class E : B { public A(ObjType MyObj) : base(MyObj){} }

If that is the case, is it better to just implement a method in the base then have my factory immediately call the method after creating the object?

like image 505
John Spiegel Avatar asked Feb 28 '12 16:02

John Spiegel


2 Answers

No it's not possible to call a non-default base constructor implicitly, you have to make it explicit.

like image 30
BrokenGlass Avatar answered Sep 19 '22 02:09

BrokenGlass


Implicitly? No, constructors are not inherited. Your class may explicitly call it's parent's constructor. But if you want your class to have the same constructor signatures as the parent class's, you must implement them.

For example:

public class A
{
    public A(int someNumber)
    {
    }
}

// This will not compile becase A doesn't have a default constructor and B 
// doesn't inherit A's constructors.
public class B : A
{
}

To make this work you'd have to explicitly declare the constructors you want B to have, and have them call A's constructors explicitly (unless A has a default constructor of course).

public class B : A
{
    public B(int someNumber) : base(someNumber)
    {
    }
}
like image 65
James Michael Hare Avatar answered Sep 19 '22 02:09

James Michael Hare