Calling new on an interface

Interesting thing: technically there is a way to call new on an interface to create an object. How? Using a feature in the C# compiler for COM-interop support:

 using System.Runtime.InteropServices;

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

class Foo : IFoo
{
}

[ComImport]
[Guid("DC1CB768-0BE5-4200-8D0A-C844BFBE3DE7")]
[CoClass(typeof(Foo))]
interface IFoo
{
}

Here you specify that Foo is a CoClass for the interface IFoo using the three attributes CoClass, ComImport and Guid. It does not matter that no real COM objects are involved, C# compiler is fine with that. What it does, it replaces the call to the IFoo() "constructor" to the equivalent constructor on the co-class Foo.

Interestingly enough, Foo doesn't have to even implement IFoo - the program will compile just fine and it will create an instance of type Foo at runtime, but it will fail when we try to put an object of type Foo into a local variable of type IFoo.

It's yet another way to instantiate a type without mentioning it in source code. As such, it can potentially be a way to achieve what factory methods do - instead of mentioning the concrete type in instantiations all over your code, you can just have a centralized place where you say what type to instantiate. With this you can easily substitute the concrete type via the CoClass attribute.

However, this is not as powerful as factory methods (you have to recompile your app to change concrete class and you can't have multiple concrete types at the same time).

I wouldn't encourage using this stuff anyway because this will probably confuse readers who read your source. But despite of anything, this *is * an interesting technique.