.NET Framework - Value Types vs Reference Types




Value Types

Reference Types

Definition: A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data.
  • All numeric data types

  • Boolean , Char, and Date

  • All structures, even if their members are reference types

  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

  • String

  • All arrays, even if their elements are value types

  • Class types, such as Form

  • Delegates

Holds Actual Data: Yes No
Pointer to another memory location: No Yes
Example: Char, Integer Class, Object, String
Memory Allocation: On stack or in-line in structure On heap

.NET Framework - Boxing and Unboxing




Now that we have seen difference between Value Types and Reference Types lets look at how can we convert value type to reference type and vice versa.

  Boxing Unboxing

Conversion of:

 Value type to Reference type.  Reference type to Value type.
Process of : Boxing is the process of converting a value type  to the type object or to any interface type implemented by this value type. Unboxing extracts the value type from the object.
How it works: Boxing a value type allocates an object instance on the heap and copies the value into the new object. For the unboxing of value type to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type.
Stores at: Reference type stored at managed (garbage-collected) heap. Value type stored at stack.
For Example:
int i = 123;
// The following line boxes i. 
object o = i; // implicit boxing
object ob = (object)i; // explicit boxing
int i = 123;   // a value type 
object o = i;   // boxing 
int j = (int)o;  // unboxing


What is a GAC?

  • Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache.

  • The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.​​

The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. 

Starting with the .NET Framework 4, the default location for the global assembly cache is %windir%\Microsoft.NET\assembly.

In earlier versions of the .NET Framework, the default location is %windir%\assembly.