Why is it possible to implement an interface?

As far as I know, interfaces cannot be created.

If so, then why compile and execute the code below? 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:

This only happens when declaring an array. Not a single copy.

+7
variables c # interface instance
source share
5 answers

You are not creating an interface, but an array of that interface.

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

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

Creating an instance of the interface will not compile:

 var bar = new IDynamicCode<string>(); 
+16
source share

You are not creating an instance of the interface; you create an array that can contain several objects that match IDynamicCode . Initially, entries have a default value of null .

+13
source share

this does not create an interface variable

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

+6
source share

Just an interesting note:

While it is not possible conceptually, syntactically , it is really possible to create an instance of an interface under certain circumstances.

.NET has something called CoClassAttribute that tells the compiler to interpret the marked interface as a specific type. Using this attribute will make the following code completely correct and will not display a compile-time error (note that this is not an array, as in the original message):

 var x = new IDynamicCode<string>(); 

A typical declaration of such an 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 ever be used, and if, then where? The answer is "mostly never"! However, there are several scenarios specific to COM interoperability where this will be a useful feature.

You can read more about the topic at the following links:

+5
source share

when you call

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

Constructors are not called. They are announced only.

+3
source share

All Articles