In this article we will discuss about boxing and unboxing in C#.Net.
You can also check various posts on:
- Difference between Abstract Class and Interface in C#.Net
- Working with enterprise library for data access in asp.net Part-3
- How to give Tooltips in WPF in Asp.Net?
Boxing:
Boxing is the process of transforming a value type to a reference type. Basically, the runtime creates a temporary reference-type box for the object on the heap.
This can happen explicitly or implicitly.
Example:
int number = 20;
object objNumber = number;
Here integer number which is value type is converted to object type which is reference type.
Unboxing:
Unboxing is the reverse process. Unboxing is the process of transforming a reference type to a value type.
But the referece type should be previously boxed. Here the value of a previously boxed value
type is cast back to a value type. And it should be done explicitly.
Here is a point to remember while doing unboxing: A variable can be unboxed only if it has been boxed.
int number = 10;
object objNumber = number; // Box the int
int number1 = (int)objNumber; // Unbox it back into an int
You can also check various posts on:
- Difference between Abstract Class and Interface in C#.Net
- Working with enterprise library for data access in asp.net Part-3
- How to give Tooltips in WPF in Asp.Net?
Boxing:
Boxing is the process of transforming a value type to a reference type. Basically, the runtime creates a temporary reference-type box for the object on the heap.
This can happen explicitly or implicitly.
Example:
int number = 20;
object objNumber = number;
Here integer number which is value type is converted to object type which is reference type.
Unboxing:
Unboxing is the reverse process. Unboxing is the process of transforming a reference type to a value type.
But the referece type should be previously boxed. Here the value of a previously boxed value
type is cast back to a value type. And it should be done explicitly.
Here is a point to remember while doing unboxing: A variable can be unboxed only if it has been boxed.
int number = 10;
object objNumber = number; // Box the int
int number1 = (int)objNumber; // Unbox it back into an int