C# – How to inherit constructors

cconstructorinheritance

Imagine a base class with many constructors and a virtual method

public class Foo
{
   ...
   public Foo() {...}
   public Foo(int i) {...}
   ...
   public virtual void SomethingElse() {...}
   ...
}

and now i want to create a descendant class that overrides the virtual method:

public class Bar : Foo 
{
   public override void SomethingElse() {...}
}

And another descendant that does some more stuff:

public class Bah : Bar
{
   public void DoMoreStuff() {...}
}

Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?

Is there no way to inherit constructors? Is there no way to encourage code reuse?

Best Answer

Yes, you will have to implement the constructors that make sense for each derivation and then use the base keyword to direct that constructor to the appropriate base class or the this keyword to direct a constructor to another constructor in the same class.

If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like null and only expose the necessary ones through their constructors.

Update

In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.