AsValeO
AsValeO

Reputation: 3039

Why is interface variable instantiation possible?

As far as I know, interfaces cannot be instantiated.

If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible?

Interface:

public interface IDynamicCode<out TCodeOut>
{        
    object DynamicClassInstance { get; set; }
    TCodeOut Execute(string value = "");
}

InCode:

var x = new IDynamicCode<string>[10];

Result:

Result

UPDATE:

It only happens when array declared. Not a single instance.

Upvotes: 7

Views: 1609

Answers (5)

Jaanus Varus
Jaanus Varus

Reputation: 3573

Just an interesting side-note:

While not possible conceptually, syntactically it is indeed possible to instantiate an interface under specific circumstances.

.NET has something called a CoClassAttribute which tells the compiler to interpret marked interface as specified concrete type. Using this attribute would make the following code perfectly valid and not throw a compile time error (note that this is not an array as in the original post):

var x = new IDynamicCode<string>();

A typical declaration of such attribute would look like this:

[ComImport]
[Guid("68ADA920-3B74-4978-AD6D-29F12A74E3DB")]
[CoClass(typeof(ConcreteDynamicCode<>))]
public interface IDynamicCode<out TCodeOut>
{
    object DynamicClassInstance { get; set; }
    TCodeOut Execute(string value = "");
}

Should this attribute be ever used and if, then where? The answer is "mostly never"! However, there are a couple of scenarios specific to COM interop where this will provide to be a useful feature.

More can be read about the topic from the following links:

Upvotes: 5

fatihk
fatihk

Reputation: 7929

when you call

var x = new IDynamicCode<string>[10];

Constructors are not called. They are only declared.

Upvotes: 3

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

this is not creating an interface variable

this will create an array where each element implements the interface. if you write x[0] = new IDynamicCode<string>(); then you will get the error. all of the elements are null, so you need to assign each element an object which implements IDynamicCode

Upvotes: 6

Glorfindel
Glorfindel

Reputation: 22651

You're not creating an instance of the interface; you're creating an array which can hold a number of objects which conform to IDynamicCode. Initially, the entries have their default value, which is null.

Upvotes: 13

CodeCaster
CodeCaster

Reputation: 151730

You're not instantiating an interface, but an array of that interface.

You can assign an instance of any class that implements IDynamicCode<string> to that array. Say you have public class Foo : IDynamicCode<string> { }, you can instantiate that and assign it to an element of that array:

var x = new IDynamicCode<string>[10];
x[5] = new Foo();

Instantiating the interface would not compile:

var bar = new IDynamicCode<string>();

Upvotes: 17

Related Questions