Why are we not allowed to specify a constructor in an interface? [duplicate]

Possible Duplicate:
Interface defining a constructor signature?

I know that you cannot specify a constructor in an interface in .Net, but why can we not?

It would be really useful for my current project to be able to specify that an 'engine' must be passed in with the constructor, but as I cant, I have to suffice with an XML comment on the class.


Because an interface describes behaviour. Constructors aren't behaviour. How an object is built is an implementation detail.


How would you call the constructor? When you use interfaces, you normally pass an instance of the interface around (or rather, a reference). Also bear in mind that if one class implements an interface, a derived class inherits that interface, but may not have the same set of constructors.

Now, I can see the use of what I call static interfaces for specifying constructors and other essentially static members for use in generic methods. See my blog post on the idea for more information.


No you can not have constructors on interfaces for the reasons that have been posted. However you can on abstract classes. Lets say for example you have this base class.

public abstract class ClassOne
{
    protected int _x;
    protected string _s;

    public ClassOne(int x, string s)
    {
        _x = x;
        _s = s;
    }        
}

Notice there is no constructors that takes no argument (default constructor) which means any class that inherits from ClassOne must call the constructor that has 2 arguments.

So this is not valid and will not compile.

public class ClassTwo : ClassOne
{
    public ClassTwo() 
    { }
}

However this is valid and will compile.

public class ClassTwo : ClassOne
{
    public ClassTwo(int x, string s) : base(x, s)
    {  }
}

I would like to point out here that in C# you can only inherit from one base class. Meaning that this may not be the correct solution for particular situation but is something to think about.

Tony.