Eric Lippert, author of the excellent blog Fabulous Adventures In Coding, has written two post discussing chained user-defined explicit conversions and some interresting details on how the compiler deals with them. Definitively worth reading - but what inspired this post was something that Jeroen Frijters wrote in his comment on the post:
"If an interface has System.Runtime.InteropServices.CoClassAttribute, the compiler will allow you to instantiate it..."
Now, I'm a straight up managed code guy and haven't got a lot of experience working with COM interop besides the odd DllImport - but this just sounded too interresting to pass up on investigating a bit closer...
Consider the following code:
class Program
{
static void Main(string[] args)
{
ITest wtf = new ITest(); // yep, that's an interface we're new'ing...
wtf.DoStuff();
Console.ReadLine();
}
}
Surely, that won't compile? Yes it will, and it will run fine too - if we declare ITest as follows:
[CoClass(typeof(Test)), ComImport, Guid("C2871EB5-CDE1-4d57-BDE0-505CAA30A4A5")]
public interface ITest
{
void DoStuff();
}
public class Test : ITest
{
#region ITest Members
public void DoStuff()
{
Console.WriteLine("WTF!");
}
#endregion
}
Go on, try it out... Probably not exactly what the CoClass attribute was meant to be used for, and you probably shouldn't either - but it sure is cool, and will definitively throw your co-workers off ;)