Friday, 24 June 2011

Reference Types and Value Types

Types in the .NET Framework come in two varieties: value types and reference types. The primary difference between value types and reference types has to do with the way variable data is accessed. To understand this difference, a little bit of background on memory dynamics is required.
All of the data associated with a value type is allocated on the stack. When a variable of a value type goes out of scope, it is destroyed, and its memory is reclaimed. A variable of a reference type, on the other hand, exists in two memory locations. The actual object data is allocated on the heap. A variable containing a pointer to that object is allocated on the stack. When that variable is called by a function, it returns the memory address for the object it refers to. When that variable goes out of scope, the reference to the object is destroyed, but the object itself is not. If any other references to that object exist, the object remains intact. If the object is left without any references to it, it is subject to garbage collection

No comments:

Post a Comment