EvilCode #14 : Can you instantiate an interface using new operator ?

In C#, can an interface or abstract class be instantiated using the “new” operator ?

This probably is one the oldest questions one might have heard as a programmer. And the most obvious answer is a big NO.

Well, at this point, I would say it is partially INCORRECT.

Why and How

The answer “Yes” is perfect for abstract classes, however, the answer is incomplete when concerned interface. Truth said, interfaces could be instantiated under a special condition.

The trick lies with the ComImportAttribute. The ComImportAttrbiute, specifies that the type decorated was previously defined in a unmanaged libary and is used for plumping COM.

Consider the following code.

[ComImport]
[Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")]
[CoClass(typeof(Person))]
publicinterfaceIPerson
{
    string FirstName { get; set; }
    string LastName { get; set; }
}

publicclassPerson : IPerson
{
    publicstring FirstName { get; set; } = "John";
    publicstring LastName { get; set; } = "Doe";
}

As you can observe the interface IPerson is decorated with ComImportAttribute. Additionally, it is also decorated with CoClassAttribute which identifies the concrete implementation that needs to be instantiated behind the scenes. Now you could instantiate the interface IPerson as the following.

var person = new IPerson();

Console.WriteLine($"Name : {person.FirstName} {person.LastName}");

// output// Name : John Doe 

As demonstrated, the question of whether a interface can be instantiated is tricky. You need to be specific when answering it. Also do note that the COMImportAttribute should be strictly restricted to COM as it involves a lot of overhead.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s