c# - How to inherit constructors?

ID : 20445

viewed : 17

Tags : c#inheritanceconstructorc#

Top 5 Answer for c# - How to inherit constructors?

vote vote


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.


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.

vote vote


387 constructors?? That's your main problem. How about this instead?

public Foo(params int[] list) {...} 
vote vote


Yes, you have to copy all 387 constructors. You can do some reuse by redirecting them:

  public Bar(int i): base(i) {}   public Bar(int i, int j) : base(i, j) {} 

but that's the best you can do.

vote vote


Too bad we're kind of forced to tell the compiler the obvious:

Subclass(): base() {} Subclass(int x): base(x) {} Subclass(int x,y): base(x,y) {} 

I only need to do 3 constructors in 12 subclasses, so it's no big deal, but I'm not too fond of repeating that on every subclass, after being used to not having to write it for so long. I'm sure there's a valid reason for it, but I don't think I've ever encountered a problem that requires this kind of restriction.

vote vote


Don't forget that you can also redirect constructors to other constructors at the same level of inheritance:

public Bar(int i, int j) : this(i) { ... }                             ^^^^^ 

Top 3 video Explaining c# - How to inherit constructors?