How is it possible to initialize an interface?

It was an interop ability of COM

Microsoft.Office.Excel API including the Application class, are written in C++

Due to architectural in C++ are more freedom, initialize an interface is needed in some case

.

.NET uses CoClass attribute on a COM object to workaround with initiate an interface

C# wont allow to initiate an interface, but with a CoClass attribute, the interface initialization can be routed to the class CoClass

(example code worth thousand words) So lets reproduce this workaround:

[CoClass(typeof(SugarGlider))] 
[ComImport] // pretend as a COM class
[Guid("000208D5-0000-0000-C000-000000000046")] // put it randomly just to fool the ComImport
public interface ISquirrel
{
     string Foo();
}

[ClassInterface(ClassInterfaceType.None)]
public class SugarGlider : ISquirrel
{
    public string Foo(){ return "Bar"; }
}

You can now initiate the interface by new ISquirrel()

Full example and runs online: https://rextester.com/ORAZQ51751


The magic is happening because of the CoClass attribute. It declares that the interface Application is to be implemented by ApplicationClass

That’s why the compiler allows Application excel = new Application(); since it can infer what class to instantiate (i.e. ApplicationClass)

What does the C# CoClass attribute do?

How does the C# compiler detect COM types?


It uses CoClass attribute, which is a COM concept. That attribute allows you tell the compiler that your interface will be implemented by Application class, thus allows you to instantiate the interface like that.

Tags:

C#

.Net

Interface