¿Por qué hay interfaces en tipos de referencia .Net?

Why are interfaces reference types? As far as I understand, an interface is a contract between classes (or structs), so why is it a type at all? I would have thought it is neither a value type or a reference type.

preguntado el 09 de enero de 11 a las 08:01

Why do you say an interface is a reference type? -

Well, I was just taking a practice exam for 70-536, and it said that interfaces are one of the things that are a reference type (along with classes and delegates). -

@nader it is a reference type... -

@Mar... yeah I really wasn't thinking straight. I was thinking that an interface isn't really anything. But something that implements an interface must treated as a reference type... -

2 Respuestas

To be treated as a struct the compiler must know en tiempo de compilación what the concrete type is, to reserve the right space on the stack. This means that aunque a struct implements IFoo, then with:

var ms = new MyStruct();
IFoo foo = ms;

then the assignment to foo is a boxing operation. You could say "the compiler should spot that it is only ever a foo and use the 'constained' opcode", but en el caso general (with multiple assignments to foo etc) this isn't possible (I would hazard a guess that it will hit the "halting problem").

There is also an issue of virtual vs static call, but the "constrained" opcode works around that.

Basically, any usage of the interface must always be treated as a reference.

There is one exception to this: generic constraints.

Si tienes

static void DoBar<T>(T target) where T : IFoo {

here the method is JITted once per value-type, so the stack-space needed for T is known; the call to Bar is "constrained" and can be virtual or static automatically as needed.

Respondido el 09 de enero de 11 a las 12:01

Ok, I get it. So MyStruct implements foo, and it is still a value type. But once you cast MyStruct to foo, it is boxed. foo's behavior makes it a reference type. Also, foo could be assigned a value type, and then a reference type, it never knows so it has to behave as a reference type to cover all scenarios... Is this all correct? - richard

They're reference types because value types have a fixed size at compile-time, so that they can be allocated on the stack. Reference types are pointers, so the pointers are constant-size but they can point to memory of any size.

Respondido el 09 de enero de 11 a las 12:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.