Friday, December 30, 2016

Boxing and unboxing in C#

Boxing is a process to store or convert value type to an object type. In this case CLR wrap the value type to System.Object and stores it into managed heap.


     int a = 100;
     object obj = a; // boxing


Unboxing is just oposite to boxing. It extracts the value type from object.


     object obj = 123;
     int a = (int)obj; // unboxing

Boxing and unboxing are expensive processes in terms of speed or processing. When a value type is boxed, a new object must be created. And cast required for unboxing. So try to avoid boxing and unboxing and used only if the is not other better option left.

Happy coding ..!!