views:

8993

answers:

6

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 verry well.

--Edit--
There seems to be some confusion about my defenition 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.

+18  A: 

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)
    {
    }
}
Jon Skeet
I could see problems indeed, but the same goes for all other methods you define. Usually NotSupportedException is the only way out.
borisCallens
@boris: The difference is that there's always *something* to be called with normal inheritance, guaranteed by the compiler. In this case there's something which "ought" to be there but isn't.
Jon Skeet
If type A inherits from type B which in its turn implements interface I, doesn't A provide I's props and methods? From your previous sentence I deduct not, but I can't come up with an anti-example.
borisCallens
@boris: Yes, but that can't apply to constructors - because you'd want the constructor to create a Bar rather than a Foo, and there's no suitable Bar constructor. That's the problem :)
Jon Skeet
Yeah but what's wrong with that, there's no suitable Bar constructor because it doesn't satisfy the interface properly. That'd be like saying you can't define methods in interfaces because if you don't implement it, it won't work.
jsimmons
@jsimmons: No, you've missed my point. With normal interfaces, any type deriving from a type which implements an interface automatically implements the interface too. That wouldn't be the case here.
Jon Skeet
Ah I see, but would that be such an issue? It'd just mean as part of the inheritance, you'd be required to implement a certain constructor. I mean, after all construction is part of the public API that an interface is want to define. Unless it implies some larger issue in the compiler?
jsimmons
@jsimmons: Well it means a type can't implement a new interface after the first release, as it would then potentially break existing subtypes. These aren't insurmountable, but they're extra things to think about - problems that don't currently exist.
Jon Skeet
+8  A: 

You can't.

Interfaces define contracts that other objects implement and therefore have no state that needs to be initialized.

If you have some state that needs to be initialized, you should consider using an abstract base class instead.

Michael
A: 

What would you need a constructor in an interface for?
Since it cannot be instanciated, it wouldn't be called, would it?

Burkhard
no, but the types implementing the interface would ...
borisCallens
A: 

you don't.

the constructor is part of the class that can implement an interface. The interface is just a contract of methods the class must implement.

royatl
Yes and the contract would specify that the implementor needs a ctor that complies to this specific signature.
borisCallens
+2  A: 

It is not possible to create an interface that defines constructors, but it is possible to define an interface that forces a type to have a paramerterless constructor, though be it a very ugly syntax that uses generics... I am actually not so sure that it is really a good coding pattern.

public interface IFoo<T> where T : new()
{
  void SomeMethod();
}

public class Foo : IFoo<Foo>
{
  // This will not compile
  public Foo(int x)
  {

  }

  #region ITest<Test> Members

  public void SomeMethod()
  {
    throw new NotImplementedException();
  }

  #endregion
}

On the other hand, if you want to test if a type has a paramerterless constructor, you can do that using reflection:

public static class TypeHelper
{
  public static bool HasParameterlessConstructor(Object o)
  {
    return HasParameterlessConstructor(o.GetType());
  }

  public static bool HasParameterlessConstructor(Type t)
  {
    // Usage: HasParameterlessConstructor(typeof(SomeType))
    return t.GetConstructor(new Type[0]) != null;
  }
}

Hope this helps.

Jeroen Landheer
I would use the interface constructor to make sure some arguments are defenatly set (through the constructor) so a parameterless ctor is not really what I'm looking for.
borisCallens
A: 

Add a static factory method to your interface.

interface DoesThings
{
    public static doesThings MakeAThingDoer(int numberOfTimes);
    public static void DoThatThing();
}

class TextPrinter : DoesThings
{
    private int numberOfTimes;
    private string whatToPrint;

    private TextPrinter(int numberOfTimes, string whatToPrint)
    {
        this.numberOfTimes = numberOfTimes;
        this.whatToPrint = whatToPrint;
    }

    public MakeAThingDoer(int numberOfTimes)
    {
        return new TextPrinter(numberOfTimes, "Foo Bar Cheese");
    }

    public void DoThatThing()
    {
        for(int i = 0; i < numberOfTimes; i++)
        {
            Console.writeLine(whatToPrint);
        }
    }
}

As you can see, object creation is part of the interface without dictating to the implementation how that creation will occur.

DoesThings baz = TextPrinter.MakeAThingDoer(5);
baz.DoThatThing();

You can go one step further by using a factory class to create the right kind of DoesThing object at runtime based on execution conditions.

Ryan Michela
this would be an ideal solution - except you can't define a static function in a C# interface
Steven A. Lowe