Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do interface variables have value-type or reference-type semantics?

Do interface variables have value-type or reference-type semantics?

Interfaces are implemented by types, and those types are either value types or reference types. Obviously, both int and string implement IComparable, and int is a value type, and string is a reference type. But what about this:

IComparable x = 42;
IComparable y = "Hello, World!";

(The question I was trying to answer was presumably deleted because it asked whether interfaces are stored on the stack or the heap, and, as we should all be aware, it's more constructive to think of differences between value and reference types in terms of their semantics rather than their implementation. For a discussion, see Eric Lippert's The stack is an implementation detail.)

like image 882
phoog Avatar asked Dec 16 '11 22:12

phoog


2 Answers

Usually, as per the existing answers, it is a reference-type and requires boxing; there is an exception though (isn't there always?). In a generic method with a where constraint, it can be both:

void Foo<T>(T obj) where T : ISomeInterface {
    obj.SomeMethod();
}

This is a constrained operation, and is not boxed even if it is a value-type. This is achieved via constrained. Instead, the JIT performs the operation as virtual-call for reference-types, and static-call for value-types. No boxing.

like image 132
Marc Gravell Avatar answered Nov 17 '22 06:11

Marc Gravell


This is about understanding boxing and unboxing of types. In your example, the int is boxed upon assignment and a reference to that "box" or object is what is assigned to x. The value type int is defined as a struct which implements IComparable. However, once you use that interface reference to refer to the value type int, it will be boxed and placed on the heap. That's how it works in practice. The fact that using an interface reference causes boxing to occur by definition makes this reference type semantics.

MSDN: Boxing and Unboxing

like image 5
Eben Geer Avatar answered Nov 17 '22 05:11

Eben Geer