Abstract constructor in C#

AndreyAkinshin picture AndreyAkinshin · Feb 19, 2010 · Viewed 62.2k times · Source

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

Why I can't declare abstract an constructor of my class like this:

public abstract class MyClass {
    public abstract MyClass(int param);
}

Answer

tvanfosson picture tvanfosson · Feb 19, 2010

Constructors are only applicable to the class in which they are defined, that is, they are not inherited. Base class constructors are used (you have to call one of them, even if only calling the default one automatically) but not overridden by deriving classes. You can define a constructor on an abstract base class -- it can't be used directly, but can be invoked by deriving classes. What you can't do is force a derived class to implement a specific constructor signature.

It is perfectly reasonable to have a constructor defined, typically as protected, in order to define some common set up code for all derived classes. This is especially true, perhaps, when the abstract class provides some other default behavior which relies on this set up. For example:

public abstract class Foo
{
     public string Name { get; private set; }

     protected Foo( string name )
     {
         this.Name = name;
     }
}

public class Bar : Foo
{
     public Bar() : base("bar")
     {
        ...
     }
}