views:

343

answers:

4

Hi,

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 ????

A: 

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
+6  A: 

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 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.

Matt Howells
A: 

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

Robban
A: 

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
**Never** call a virtual method in a class from its constructor! http://stackoverflow.com/questions/119506
dtb
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