Default value for interface type

This might be a stupid question with the obvious answer I missed, but if I have the following:

interface A { } struct B { A some_field; } 

Then what would the default ctor of B do, like how big it would be under the hood in bytes?

In other words (and from a different perspective), what is the default value for an interface type and will it be considered as a type of reference or value, since both classes (reference) and structs (value) can inherit from it?

+4
source share
2 answers

Interfaces are reference types.

An interface type field will always have one width pointer and will be null by default.

If you assign a structure that implements the interface, the structure will be placed in the box, and the field will contain a link to the box object.

+8
source

As SLaks noted, a variable that has an interface type will behave like a control holder, which, as you know, will never contain anything but null , or a reference to an object that implements the interface. As with all link holders, the default value will be null .

A variable that has a generic type that is limited by the type of interface (for example, in a class

 Thing<T> where T:IComparable<T> {T foo; ...} 
Field

Foo will have the same default value as any actual type replaced by T For example, given

 struct SimplePoint : IComparable<SimplePoint> {public int x,y; public int CompareTo(SimplePoint other) {...} ...} 

then inside the Thing<SimplePoint> the Foo field will have a default value (0,0).

By the way, it is worth noting that although the conversion from a structure type to any reference type, including the interface that it implements, will give a link to a new heap object containing a snapshot of the structure fields, converting this link to other reference types will give a link to the same same instance of the heap.

+2
source

Source: https://habr.com/ru/post/1497469/


All Articles