1

I have a base class B with multiple constructors. I have a derived class D which has some additional fields to be set in its constructor(s), implemented as shown below.

B(args1) {...}
B(args2) {...}
...
B(argsN) {...}

D(args1, additional) : B(args1) {...}
D(args2, additional) : B(args2) {...}
...
D(argsN, additional) : B(argsN) {...}

Problem is, every time a new B constructor is added with new args I have to make a new D constructor. Any way around this?

Mat
  • 275
  • 3
  • 12
  • 1
    possible duplicate of [How to inherit constructors?](http://stackoverflow.com/questions/223058/how-to-inherit-constructors) – Jeroen Mostert Nov 19 '14 at 16:14
  • 3
    Would default values help? `D(argsN=null)`? I would think about do you always need a new constructor.. – Sayse Nov 19 '14 at 16:15
  • 2
    Create a class. Then pass an instance of it as a parameter. Just 1 constructor for each class would be needed then. Otherwise I don't think there is a way out. For class `B` it might be, let's say, `BArgs`, for D - `DArgs : Bargs`. Then you would pass `DArgs` to B constructor. `DArgs` would extend `BArgs` with your `additional` parameter. – Artem Kachanovskyi Nov 19 '14 at 16:18
  • Are you sure you can't replace constructor parameters with properties having public setters? Or *SetSomething* methods? Because in this case your maintenance will be significantly easier. – galenus Nov 19 '14 at 16:24
  • 1
    Smells like a bad design. Why `D` is inherited from `B`? Maybe `D` can simply create and hold an instance of `B`? Normally you don't choose inheritance in such scenario. And you understand, what adding `B(argsX)` doesn't **require** from `D` to implement `D(argsX, additional)`? – Sinatr Nov 19 '14 at 16:33

1 Answers1

0

You have to define a constructor in the derived class if you want it in the base class and expect them to be identical. You could, however, use default values as suggested. Or, have a dictionary-based constructor, which derived classes grab values from.

Could you use an alternative design pattern like Factory Method, Factory, or something to simplify the constructor approach?

If you really want constructors and want to add a complicated solution, use the following. NOT RECOMMENDING IT, but you could use code sharing/generation technique with a combination of partial classes (define one partial class with the constructors, and the other has all of the properties/members/etc.) and in that partial class that has the constructors, a T4 template overwrites it when the base template changes. Again, this adds A LOT of overhead... I don't know how many classes you are talking about, and how exact you want them.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257