Is it possible to inherit constructors, and if so, how? I am trying to make a class that inherits a System class, and I want the constructors of it.
4 Answers
This is not possible in vanilla C#. Constructors can't be simply inheritted. They must be redefined on every level and then chained to the parent's version.
class Parent {
internal Parent(string str) { ... }
internal Parent(int i) { ... }
}
class Child : Parent {
internal Child(string str) : base(str) { ... }
internal Child(int i) : base(i) { ... }
}
1 Comment
svick
Parameterless constructors are an exception to this rule, though. If you don't have any other constructor, they are defined automatically, calling the parameterless constructor of the base class. This means you don't have to redefine them on every level.
All the other answers so far are correct. However, understand that you do not have to match the base class constructor's signature with the constructor you are defining:
public class Base
{
public Base(string theString) { ... }
}
public class Derived:Base
{
public Derived():base("defaultValue") //perfectly valid
{ ... }
public Derived(string theString)
:base(theString)
{ ... }
public Derived(string theString, Other otherInstance)
:base(theString) //also perfectly valid
{ ... }
}
... and in addition to invoking a parent class's constructor, you can also "overload" constructors within the same inheritance level, by using the this keyword:
public class FurtherDerived:Derived
{
public FurtherDerived(string theString, Other otherInstance)
:base(theString, otherInstance)
{ ... }
public FurtherDerived()
:this("defaultValue", new Other()) //invokes the above constructor
{ ... }
}
Resharper > Edit > Generate Code.... If not, you'll have to write the constructors yourself as Erik's answer shows.