0

I have a parent and a couple of child classes. The constructor of each child class should do nothing special, but it is still needed to pass the parameter to the parent constructor. Is there a way to reach the same thing without touching the child (without adding a constructor to each child)? I have 13 child class, which should use the same constructor as the parent. (In my case, the parent class is abstract)

public class A
{ 
    private int _number;
    public A(int number)
    {
        this._number = number;
    }
}

and

public class B:A
{
    public B(int number):base(number)
    {
          //Nothing here
    }
    ...
}

Maybe I can just use the default constructor in the child class and create a static generic method in the parent class, which takes the same parameters and returns a new child:

public static T getChild<T>(int number) where T:A, new()
{
    T child = new T();
    T._number = number;
    return child;

}

But I prefer creating object with a constructor. Is there another possibility?

jasdefer
  • 757
  • 12
  • 24
  • If you want to call a constructor, there is no way around writing a constructor. On an unrelated note, if constructors of derived classes have nothing to initialize, perhaps you could change the design to avoid making so many classes in the first place. – Sergey Kalinichenko Oct 02 '14 at 09:53
  • How did you find that? I google ages for this :D Thanks, yes you are right. But maybe there is something to say to my approach with the static method – jasdefer Oct 02 '14 at 09:55
  • @jasdefer if you're curious, this is the exact google search query I've used: "c# parent constructor without child constructor" and that question is the 2nd result :-) – zerkms Oct 02 '14 at 09:56
  • What do you say to my approach with the generic method? – jasdefer Oct 02 '14 at 10:00

0 Answers0