Abstract classes> required constructor for child classes

Possible duplicate:
Why can't I create an abstract constructor in an abstract C # class?

How can I write one abstract class that says it is mandatory for a child class to have one constructor?

Something like that:

public abstract class FatherClass { public **<ChildConstructor>**(string val1, string val2) { } // Someother code.... } public class ChildClass1: FatherClass { public ChildClass1(string val1, string val2) { // DO Something..... } } 

UPDATE 1:

If I can not inherit the constructors. How can I prevent someone from FORGETTING to implement this particular constructor of the child class ????

+7
c # abstract-class
source share
4 answers

You can not.

However, you could set one constructor in FatherClass as follows:

 protected FatherClass(string val1, string val2) {} 

What forces subclasses to call this constructor is to β€œencourage” them to create the constructor string val1, string val2 , but it does not give it a mandate.

I think you should consider an abstract factory template instead. It will look like this:

 interface IFooFactory { FatherClass Create(string val1, string val2); } class ChildClassFactory : IFooFactory { public FatherClass Create(string val1, string val2) { return new ChildClass(val1, val2); } } 

If you need to instantiate a subclass of FatherClass, you use IFooFactory, not directly. This allows you to specify the signature (string val1, string val2) to create them.

+18
source share

The problem is that by default, the non abstract / static class will always have an empty empty default constructor unless you override it with private Constructor () {....}. I do not think that you can force a constructor with 2 string parameters to be present in a child class.

0
source share

You do not inherit constructors. You just need to implement it yourself in each child class.

0
source share

You cannot set the constructor as abstract, but you can do something like this:

  public abstract class Test { public Test(){} public Test(int id) { myFunc(id); } public abstract void myFunc(int id); } 
0
source share

All Articles