Reputation: 1532
This may be a stupid question with an obvious answer I overlooked but if I have the following:
interface A { }
struct B {
A some_field;
}
Then what would the default ctor of B get me as in how large would it be under the hood in bytes?
In other words (and from another perspective), what is the default value of a interface type and would it be considered a reference or value type since both classes (reference) and structs (value) can inherit from it?
Upvotes: 7
Views: 5253
Reputation: 81347
As SLaks noted, a variable which is of an interface type will behave as a reference holder which is will be known known never to contain anything other than either null
or a reference to object which implements the interface. As with all reference holders, the default value will be null
.
A variable which is of a generic type which is constrained to an interface type (e.g. in class
Thing<T> where T:IComparable<T>
{T foo;
...}
field Foo
will have the same default value as whatever the actual type substituted for T
. For example, given
struct SimplePoint : IComparable<SimplePoint>
{public int x,y;
public int CompareTo(SimplePoint other)
{...}
...}
then within Thing<SimplePoint>
, the field Foo
would have the default value (0,0).
Incidentally, it's worthwhile to note that while a conversion from a structure type to any reference type, including an interface it implements, will yield a reference to a new heap object containing a snapshot of the structure's fields, conversion of that reference to other reference types will yield a reference to the same heap instance.
Upvotes: 3
Reputation: 888273
Interfaces are reference types.
A field of an interface type will always be one pointer wide, and will default to null
.
If you assign a struct that implements the interface, the struct will be boxed, and the field will contain a reference to the boxing object.
Upvotes: 14