1

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.

2
  • 1
    No. You can have VS or R# (or another similar extension) autogenerate constructors for every base constructor though. Commented Feb 6, 2012 at 22:07
  • Seems what I was thinking of was a Resharper feature. If you have that, it's under Resharper > Edit > Generate Code.... If not, you'll have to write the constructors yourself as Erik's answer shows. Commented Feb 6, 2012 at 22:11

4 Answers 4

7

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) { ... }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
4

Constructors don't 'inherit' the same way that methods do, but you do have the option of invoking base class constructors:

public DerivedClass(Foo foo) : base(foo)

Comments

2

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
   { ... }
}

Comments

1

You can't inherit constructors; you have to call them explicitly (except for the default constructor, which is called, well, by default):

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

class B : A
{
    public B (int i) : base (i) { }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.