Type casting is converting one type of data to another type. For eg., converting from string to int or vice versa. In C#, type casting has two forms:
- Implicit Type conversion: These conversions are performed by C# in a type-safe manner. For example, conversions from smaller to larger integral types and conversions from derived classes to base classes.
- Explicit Type conversion: These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.
C# boxing and unboxing
C# Type system contains three types they are called Value types, Reference Types and Pointer Types. C# allows us to convert a value type to a reference type, and back again to value type. The operation of converting a value type to a reference type is called Boxing and the reverse operation is called Unboxing.
Boxing:
- int Val = 10;
- Object Obj = Val; //Boxing
The first line we created a Value type Val and assigned a value to Val. The second line, we created an instance of Object Obj and assign the value of Val to Obj. From the above operation (Object Obj = Val) it comes to know that converting a value of a Value Type into a value of a corresponding Reference Type. These types of operation is known as Boxing.'
Unboxing:
- int Val = 10;
- Object Obj = Val; //Boxing
- int i = (int)Obj; //Unboxing
The first two line is about boxing a Value Type. The third line (int i = (int)Obj ) extracts the Value type from the Object. That is converting a value of a reference type into a value of Value type. This operation is known as Unboxing.