Reactgular
Reactgular

Reputation: 54811

How to avoid implementing empty constructors in derived classes?

I have a base class that has a large number of derived classes, and the base class has several constructors. In all my derived classes I have to implement empty constructors to forward the arguments to the base constructors. Is it possible to somehow tell C# to use the derived constructors?

For example, if using this base class.

 class BaseTool
 {
      public BaseTool(string Arg1, string Arg2)
      {
          // do stuff.
      }

      public BaseTool(string Arg1)
      {
          // do stuff.
      }

      public BaseTool(int Arg1)
      {
          // do stuff.
      }
  }

I would have to implement all the above constructors with those arguments, and then call : base(...) to forward them to the derived class. This is resulting in a lot of classes that have empty constructors. Seems like a lot of wasted code.

Upvotes: 3

Views: 491

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

(Promoted from a comment, by request.)

The only thing I can think of is making static methods instead of instance constructors. So for example:

class BaseTool
{
  public static T Create<T>(string Arg1, string Arg2) where T : BaseTool, new()
  {
    var instance = new T();
    // do stuff, to instance (which is a BaseTool)
    return instance;
  }

  public static T Create<T>(string Arg1) where T : BaseTool, new()
  {
    var instance = new T();
    // do stuff, to instance (which is a BaseTool)
    return instance;
  }

  public static T Create<T>(int Arg1) where T : BaseTool, new()
  {
    var instance = new T();
    // do stuff, to instance (which is a BaseTool)
    return instance;
  }
}

This could be called as:

var newDT = BaseTool.Create<DerivedTool>("foo", "bar");

or, from inside some BaseTool (since methods are inherited, in contrast to constructors), just:

var newDT = Create<DerivedTool>("foo", "bar");

I know it's a little less elegant than var newDT = new DerivedTool("foo", "bar");.

Upvotes: 2

dtb
dtb

Reputation: 217351

Constructors are not inherited from base classes, so there is no way around declaring all constructors in each derived class. However, you could automate this repetitive task with, for example, T4 Templates.

Upvotes: 4

Related Questions