1

from a url i saw people can instantiate interface like this way

class Program
{
    static void Main(string[] args)
    {
        var foo = new IFoo(1);
        foo.Do();
    }
}

[
    ComImport, 
    Guid("C906C002-B214-40d7-8941-F223868B39A5"), 
    CoClass(typeof(FooImpl))
]
public interface IFoo
{
    void Do();
}

public class FooImpl : IFoo
{
    private readonly int i;

    public FooImpl(int i)
    {
        this.i = i;
    }

    public void Do()
    {
        Console.WriteLine(i);   
    }
}

how it is possible to write like this var foo = new IFoo(1); looking for guidance. thanks

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 6
    It isn't. I suggest stopping asking all those interface question and read some material about interfaces and polymorphism in C#. – Samuel Feb 20 '14 at 09:04
  • 1
    see http://stackoverflow.com/questions/1303717/newing-up-interfaces?rq=1 – rt2800 Feb 20 '14 at 09:07
  • 2
    @Samuel It *does* work. – dcastro Feb 20 '14 at 09:08
  • Even if possible, this would just make the whole `interface` idea useless, the big question is: Why would you *ever* want to do this? – Jite Feb 20 '14 at 09:09
  • @Thomas: did you follow the [documentation guidelines](http://msdn.microsoft.com/en-us/library/hh708954.aspx) about adding a reference to a COM object? – Steve B Feb 20 '14 at 09:13
  • 1
    @dcastro This was indeed new to me. Thomas please accept my apology on the first sentence. I've learnt something new today. Beside COM specific attributes this is not a common approach when working with interfaces. And I still recommend concentrating on base interface concepts introduction. – Samuel Feb 20 '14 at 09:33
  • Looks like he's asking about the code from [Instantiating interfaces - Ayande](http://ayende.com/blog/4121/instantiating-interfaces). – Sam Feb 20 '14 at 09:34

1 Answers1

6

That's just how COM works. You've declared FooImpl to be IFoo's coclass. new IFoo(1); will be compiled to new FooImpl(1);

According to §17.5 of the C# specification, attributes under the System.Runtime.InteropServices namespace may break all the rules. This is specific to Microsoft's C# implementation.

Marc Gravell and Jon Skeet have really good blog posts about this: Who says you can’t instantiate an interface? and Faking COM to fool the C# compiler

dcastro
  • 66,540
  • 21
  • 145
  • 155