Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface defining a constructor signature?

It's weird that this is the first time I've bumped into this problem, but:

How do you define a constructor in a C# interface?

Edit
Some people wanted an example (it's a free time project, so yes, it's a game)

IDrawable
+Update
+Draw

To be able to Update (check for edge of screen etc) and draw itself it will always need a GraphicsDeviceManager. So I want to make sure the object has a reference to it. This would belong in the constructor.

Now that I wrote this down I think what I'm implementing here is IObservable and the GraphicsDeviceManager should take the IDrawable... It seems either I don't get the XNA framework, or the framework is not thought out very well.

Edit
There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.

like image 360
Boris Callens Avatar asked Mar 06 '09 18:03

Boris Callens


People also ask

Can you define a constructor in an interface?

No, you cannot have a constructor within an interface in Java. You can have only public, static, final variables and, public, abstract, methods as of Java7. From Java8 onwards interfaces allow default methods and static methods.

What is the correct signature for the constructor?

Constructors have no return type and always use the name of the class in which they are declared [3]. Similarly to method signatures, a constructor signature is made up of the constructor name and a comma-delimited list of input parameters enclosed in parentheses.

Can we define constructor in interface C#?

The technical answer is that you can't; defining a constructor on an Interface is not allowed in any programming language that I know of, definitely not in C#.

Should I put constructor in interface?

In order to call any method we need an object since there is no need to have object of interface, there is no need of having constructor in interface (Constructor is being called during creation of object).


1 Answers

You can't. It's occasionally a pain, but you wouldn't be able to call it using normal techniques anyway.

In a blog post I've suggested static interfaces which would only be usable in generic type constraints - but could be really handy, IMO.

One point about if you could define a constructor within an interface, you'd have trouble deriving classes:

public class Foo : IParameterlessConstructor {     public Foo() // As per the interface     {     } }  public class Bar : Foo {     // Yikes! We now don't have a parameterless constructor...     public Bar(int x)     {     } } 
like image 50
Jon Skeet Avatar answered Oct 09 '22 15:10

Jon Skeet