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:
UPDATE:
It only happens when array declared. Not a single instance.
In an interface, you can't instantiate variables and create an object.
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.
Interface variables are static because java interfaces cannot be instantiated on their own. The value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned.
Declaring final variable without initializationIf you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't you will get a compilation error.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With