Alex Rivera | Logout

How to define the default implementation of an interface in c#?

Asked 2010-07-17T11:09:42.523
31

There is some black magic code in c# where you can define the default implementation of an interface.

So you can write

var instance = new ISomeInterface();

Any pointers?

UPDATE 1: Note that I did not ask if this is a good idea. Just how was it possible to do it.

UPDATE 2: to anyone seeing the accepted answer.

  • "this should be treated merely as a curiosity." from Marc Gravel "Newing up" Interfaces
  • "It's a bad idea to use a tool designed for COM interop to do something completely and utterly different. That makes your code impossible to understand for the next guy who has to maintain it" from Eric Lippert "Newing up" Interfaces
  • "While it may work, if it were ever found in production code by a rational coder, it would be refactored to use a base class or dependency injection instead." from Stephen Cleary in a comment below.
Edit
Report

2 Answers

34

Here comes the black magic:

class Program
{
    static void Main()
    {
        IFoo foo = new IFoo("black magic");
        foo.Bar();
    }
}

[ComImport]
[Guid("C8AEBD72-8CAF-43B0-8507-FAB55C937E8A")]
[CoClass(typeof(FooImpl))]
public interface IFoo
{
    void Bar();
}

public class FooImpl : IFoo
{
    private readonly string _text;
    public FooImpl(string text)
    {
        _text = text;
    }

    public void Bar()
    {
        Console.WriteLine(_text);
    }
}

Notice that not only you can instantiate an interface but also pass arguments to its constructor :-)

answered 2010-07-17T11:40:50.350
3

Only if ISomeInterface is a class.

Update (for clarification):

Jon Skeet has a talk where he mentions default implementations for interfaces. They are not part of the C# language, though. The talk is about what Jon Skeet would like to see in a future version of C#.

For now, the only default implementations are done via (possibly abstract) base classes.

answered 2010-07-17T11:14:24.483

Your Answer