Answer: Instantiating an interface


Well, that was a fun little quiz… I should have added “no scoping tricks” to the list of rules, but what Roy Osherove suggested does work.  But Kevin Dente  gives the answer I was looking for.  Whenever you see something funny going on in the framework 9 out 10 times it is because of Com Interop ;-)… go figure:

 

using System.Runtime.InteropServices;

 

[CoClass(typeof(Foo))]

[Guid(“00000000-0000-0000-0000-000000000000”)]

[ComImport]

interface IFoo { }

 

public class Class1 {

    static void Main() {

        new IFoo();

    }

}

class Foo : IFoo { }

 

 

Thanks again to the folks down-under for suggesting this quiz. 

 

Comments (2)

  1. Keith Patrick says:

    I don’t have Whidbey to play with, but I know it’s got anonymous methods; if it has anonymous classes as well, you could do something like this (used to do this in Java for quick & dirty event handlers):

    static void Main() {

    new IFoo() { public void FooMethodImpl() {} };

    }

    I hope I got the syntax right…been a while since I’ve written Java, much less Swing apps.

  2. Someone asked me to provide more background on this one.. here it is from the owner of the ComInterop support in the CLR:

    In the case of COM objects, all the CLR has is an interface: the object is defined in the COM dll and its only contract is that interface. Therefore if you want to use a COM object that you import (or in the example define and interface and guid for) you can “new” the interface and the runtime will find the COM component that implements that interface and give you one.