Boris Callens Boris Callens - 26 days ago 18
C# Question

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.

Answer

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)
    {
    }
}
Comments