Monday 16 June 2014

What is the difference between Value and Reference Types?

Purpose
  • The original question only revolved around the String case that is somewhat unique in that it is a reference type that is purposely coded to be immutable (behave like a value type)
  • An understanding of memory allocation and management shows a deep knowledge of the nuts and bolts of the framework and is a good sign.

Potential Answers:

Value Type
When a variable is declared using one of the basic, built-in data types or a user defined structure, it is a value type. An exception is the string data type, which is a reference type.
A value type stores its contents in memory allocated on the stack that is a thread specific memory construct in RAM that allows for fast allocation of memory for types with a known size. When the variable goes out of scope because the method in which it was defined has finished executing, the value is discarded from the stack immediately meaning that no explicit memory management is needed.
Reference Type
A reference type, such as an instance of a class or an array, is allocated in a different area of memory called the heap that is a slower area of allocation in RAM but is more flexible in that you don't need to know the size of your allocation beforehand. Unlike the stack this memory is never destroyed when it falls out of scope and as such it needs to be explicitly managed to avoid memory leakage.
In the managed programming world like .NET, This memory isn't returned to the heap when a method finishes; it's only reclaimed when the garbage collection system determines it is no longer needed. There is a greater overhead in declaring reference types, but they have the advantage of being accessible from other classes.

No comments:

Post a Comment