8

Possible Duplicate:
Why can’t I create an abstract constructor on an abstract C# class?

How can I write one abstract class that tells that is mandatory for the child class to have one constructor?

Something like this:

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't inherit constructors. How can I prevent that someone will NOT FORGET to implement that specific child class constructor ????

Community
  • 1
  • 1
SmartStart
  • 657
  • 1
  • 6
  • 8

4 Answers4

20

You cannot.

However, you could set a single constructor on the FatherClass like so:

protected FatherClass(string val1, string val2) {}

Which forces subclasses to call this constructor - this would 'encourage' them to provide a string val1, string val2 constructor, but does not mandate it.

I think you should consider looking at the abstract factory pattern instead. This would 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);
    }
}

Wherever you need to create an instance of a subclass of FatherClass, you use an IFooFactory rather than constructing directly. This enables you to mandate that (string val1, string val2) signature for creating them.

nawfal
  • 70,104
  • 56
  • 326
  • 368
Matt Howells
  • 40,310
  • 20
  • 83
  • 102
0

The problem is that be default a non abstract / static class will always have a default empty public constructor unless you override it with private Constructor(){....}. I don't think you can force a constructor with 2 string params to be present in a child class.

Colin
  • 10,630
  • 28
  • 36
0

You do not inherit constructors. You would simply have to implement one yourself in every child class.

Robban
  • 6,729
  • 2
  • 39
  • 47
0

You cant set a 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);
    }
Sergio
  • 8,125
  • 10
  • 46
  • 77
  • 1
    **Never** call a virtual method in a class from its constructor! http://stackoverflow.com/questions/119506 – dtb Sep 08 '09 at 12:16
  • 3
    dtb: Your link explains why not to invoke virtual methods on a Constructor, it's not quite the same as abstract methods. Never the less, I don't see why not if it is used a proper name and documentation. – Sergio Sep 08 '09 at 12:42