.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.
Includes:
  • 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
Diagram:
https://i-msdn.sec.s-msft.com/dynimg/IC97798.gif

https://i-msdn.sec.s-msft.com/dynimg/IC135292.gif