Tuesday, 10 December 2013

Boxing VsUnBoxing And Value Types Vs Reference Types

What is Boxing and UnBoxing in .Net



Converting value type to reference type is called boxing and converting reference type to value type is called as unboxing.
Eg:
int i=1;
object o=i;  --> Boxing
int j=(int) o;  -->unboxing  
   
Boxing and unboxing are only the technical terms for type casting from value type to reference type and vice versa.

Access to value types will be fast when compared to reference types. Because they directly contain the value and no need to refer another memory location.

It is recommended to avoid boxing and unboxing in the program wherever it is possible. Because these operations take time and will affect the performance of the application.



Boxing
Unboxing
Definition:
Boxing is the process of converting a value type to the reference type.
Unboxing is the process of converting
a reference type to value type
.
Type of Conversion:
Implicit Conversion
Explicit Conversion

Example:
int i = 221;
object obj = i; //boxing
object obj = 213;
i = (int)obj ; // unboxing


What are Value Types and Reference Types in .Net


           According to MSDN,   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 the data types in .net are classified in to value types and reference types. 
 

  • The data types whose values are directly stored in stack memory area are called as value types and the data types whose values are stored in heap memory area and its address is stored in a variable in stack memory area are called as reference types.
  • Among all built in data types of .net string and object are reference type and all other data types are value types.
  • Among user defined data types, class, interface, delegate and arrays are reference type while structure and enumeration are value type.
Value Types----------------
Value types include the following:

  • 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
Reference Types
----------------------
Reference types include the following:

  • String
  • All arrays, even if their elements are value types
  • Class types
  • Delegates

No comments:

Post a Comment