52

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.

Community
  • 1
  • 1
Pondidum
  • 11,457
  • 8
  • 50
  • 69

7 Answers7

94

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

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 26
    I think that's putting attaching too much meaning to an implementation detail: a constructor in .NET is really just a method that gets called immediately after the object is created (allocated in memory). There is no reason it can't be defined as behaviour as well. Of course, implementations are free to declare other constructors as well, just as they can overload a method that implements an interface. Constructors in interfaces would be a rarely-used feature, but not a useless one. – EMP May 19 '10 at 04:42
  • 1
    I think the point of the question is: since it is built this way, what is the best practice? So I suppose the answer is: by using abstract classes, as this answer states: http://stackoverflow.com/a/2804067/1181162 – Vince Oct 22 '12 at 09:39
  • A public constructor is obviously part of the API. What else could that be if not behaviour? – Soundbytes Oct 22 '19 at 14:11
28

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1 I think this would be a great addition to .NET and I've upvoted the associated Connect feedback item: https://connect.microsoft.com/VisualStudio/feedback/details/412848/allow-structural-type-constraints-for-generic-type-parameters – EMP May 19 '10 at 05:02
  • 1
    I can think of three class-ish features of interfaces: (1) default implementations for methods or properties (note that inherited interfaces would not be able to override those of the base); (2) allowing the same identifier to effectively double as an interface and a static class; (3) defining a static method to be used when "new" is called on the interface. Note that #2 and #3 would be syntactic sugar, but I think they'd make some things cleaner. If .net supported #1, interfaces could have new methods or properties added without breaking existing implementations. – supercat Mar 04 '11 at 01:44
  • @supercat: Yes, I've been thinking about 1 for a while too - and so has MS, I believe. There's an interview with Vance Morrison where he talks about this. – Jon Skeet Mar 04 '11 at 06:26
  • I'm curious to know what's being done re #1; I'd also like to know if Microsoft is adding any nice means of cleaning up IDisposables when constructors throw exceptions, or (for vb) if there's going to be a way to automatically kill all WithEvents subscriptions. I've seen some links for old discussions of new features; do you have anything up-to-date? – supercat Mar 04 '11 at 15:57
  • @supercat: No idea, I'm afraid. I haven't heard about anything around that. – Jon Skeet Mar 04 '11 at 16:10
  • @JonSkeet Could you explain what you mean by static interfaces? It sounds like you mean an interface that cant be instantiated, but interfaces cant be instantiated at all so that doesnt make any sense. – kingfrito_5005 Jan 27 '17 at 14:50
  • @kingfrito_5005: Did you read the blog post that I linked to? – Jon Skeet Jan 27 '17 at 15:18
  • @JonSkeet I did, but honestly I was more confused after reading it than I was going in. – kingfrito_5005 Jan 27 '17 at 15:20
  • @kingfrito_5005: In that case I suggest you ignore the whole second paragraph. I doubt that explaining it again (which would take more than a comment) will help. – Jon Skeet Jan 27 '17 at 16:38
9

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.

Tony
  • 1,684
  • 1
  • 18
  • 29
  • 1
    Since classes cant inherit constructors, I think this is only a partial solution because it requires the subclass to implement its constructor call in a special way, but doesnt guarantee that the subclass has a constructor with the same signature. – kingfrito_5005 Jan 27 '17 at 14:45
8

Among all the other reasons already posted, keep also in mind the a class can easily implement several interfaces; which constructor should be used then?

M.Turrini
  • 738
  • 1
  • 4
  • 19
  • 1
    There's a perfectly good syntax for implementing interface methods with the same signature that could be used for the constructors. – Simon Mar 27 '09 at 13:22
  • I'm not sure I got your point (maybe I didn't): I meant that class A can implement interfaces IAlpha with a constructor with no arguments, IBeta with a constructor with one arguments and IGamma with a constructor with two arguments: which constructor should class A implement? – M.Turrini Mar 27 '09 at 13:36
  • Ah, this is the only answer that really makes sense to me. All the arguments that you can't instantiate an interface leave me asking "So what?" The point of an interface is to declare that such-and-such a set of functions must be implemented in any class that presumes to implement the interface. It sounds reasonable to say that such a class should also have to implement a constructor taking this particular set of arguments. But the clashing constructors argument, now that presents a problem. – Jay May 10 '10 at 16:13
  • Totally agree with Jay. Although I believe its not an absurd idea to enforce constructor signature through interface, a lot more thought needs to be put in. – Shravan Aug 19 '10 at 20:56
  • It wouldnt be hard for .net to simply disallow the implementation of interfaces with identical method signatures. In fact, doesnt it do that? If not I think it should regardless of the constructor question. – kingfrito_5005 Jan 27 '17 at 14:41
6

Other answers have already pointed out why it doesn't make sense to have a constructor declaration on an interface. But from your question, I'm guessing that you are probably looking for the abstract factory pattern.

To give an example based on your question: you say that you would like to somehow declare that an 'engine' must be passed to the constructor. You can do this by declaring a separate interface for a construction service like this:

public interface IGadgetFactory
{
   IGadget CreateGadget(Engine engine);
}

Any code which must create IGadget instances can then use an IGadgetFactory instance instead of calling any constructors directly.

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
0

Because you cant instantiate an interface, so a constructur doenst make sense.

Mork0075
  • 5,895
  • 4
  • 25
  • 24
0

Besides the other explanations given here, you'd have to invent a new syntax for calling them anyway, since if you have two or more implementations in scope at the line:

Dim x as new IDoStuff()

Whice implementation gets called?

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • Were I designing a language, I would allow an interface to name a static method to be used, so the above statement would be equivalent to e.g. `Dim X As IDoStuff = IDoStuff_Creator.CreateNew();` – supercat Dec 06 '13 at 00:23