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.)
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.