Pergunta

I understand this topic is answered a lot. My question is specific to the way it is said or asked.

So am I right to say, that code written with a class keyword will be on the managed heap and is a reference type, and code that is written with a struct will be on stack and is a value type?

Foi útil?

Solução

I used to think like this as well. However, I recently had a nice discussion with Jon Skeet (he may provide more details) and he explained me that a value type may be kept on the heap as well. The key is how long will that variable be used. If it's a short-lived value type variable, it will be left only at the stack. However, if it's used many times, the framework will keep it at the heap to save space at the stack.

IMO, the key difference between reference and value types relies on passing the object to another object or method. If it's a reference type, you are simply sharing its reference. If it's a value type, then you are making a copy of it.

About the subject of short x long-lived variable, here is the full picture:

in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value.

Source: The Truth About Value Types (it's also on the comments)

Outras dicas

Any storage location (local variable, parameter, class field, struct field, or array slot) of a reference type will always either hold null, or else will hold a reference to an object on the heap. A storage location of a value type will hold all public and private fields of that type (a primitive value type is internally stored as a structure with one field, which is declared to be of that same primitive type; a little bit of compiler magic is used to recognize when special-case code must be used to work with that type). For every value type there is a corresponding heap-object type which has the same members; an attempt to store a value type in a reference-type storage location will create a new heap object of the appropriate heap type, copy the contents of the value-type fields to those of the new object, and store a reference to that new object in the requested storage location. This process is called "boxing". It's possible to copy the contents of a boxed heap object's fields to those of a value-type storage location, a process called "unboxing". Note that because boxed value types are accessed using reference-type storage locations, they behave like reference types rather than class types. C# tries to pretend that the type of a value-type storage location and the type of a boxed value-type instance are the same type, but the two types behave somewhat differently; pretending that they are the same simply adds confusion.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top