Wednesday 3 May 2017

Boxing and unboxing in c#.


In c# all types whether reference or value types in c# are derived from System.object base class.Boxing is the process by which you can perform implicit conversion of value type to an object type.whenever you perform boxing on a value type the CLR(Common Languge Runtime) encloses it inside System.object base class and store the value in the managed heap(In c# value types are stored in stack memory and reference types are stored on heap memory).
Example:
Int i=10;
Object ob=(object)i;  //Boxing.
Unboxing on the other hand is the reverse process of boxing.It is the process in which you can perform explicit conversion of object type in to value type .The process of unboxing example:
Object ob=123;
Int i=(int)ob;       //unboxing.

Though boxing and unboxing provides application developers the flexibilty to treat value types as reference types ,computationally, these are quite expensive operations.This is due to the fact when a value type is boxed ,an object need to be allocated and constructed.


------------------------------------Muthu karthikeyan,Madurai

No comments:

Post a Comment