Boxing and Unboxing are important concepts in C#. Boxing converts a value type into a reference type (object), whereas Unboxing converts the reference type back into its original value type. C# also supports implicit and explicit type casting for converting one data type into another.
Boxing is the process of converting a Value Type into a Reference Type (object). Boxing is performed automatically by the CLR.
Unboxing is the process of converting a Reference Type (object) back into its original Value Type. Unboxing requires explicit casting.
Type Casting is the process of converting one data type into another. C# supports both Implicit and Explicit type conversions.
Implicit (Widening) conversion is performed automatically when there is no possibility of data loss.
Explicit (Narrowing) conversion is performed manually using the cast operator when data loss may occur.
> "42"> "42"> "42"
Create an integer variable named num.
Assign the integer to an object variable. The CLR automatically converts the value type into a reference type.
Print the boxed object to the console.
Convert the object back to an integer using explicit casting.
Print the unboxed integer.
Assign an integer array to an object variable.
Study the difference between implicit and explicit type conversions.
Older collections like ArrayList store objects. When integers are added into an ArrayList, boxing occurs automatically. When retrieved, unboxing is required.
Boxing is the process of converting a Value Type into a Reference Type (object).
Unboxing converts a Reference Type back into its original Value Type.
Boxing is an implicit conversion.
Because the CLR requires the programmer to specify the target value type.
It allocates memory on the heap and decreases performance.
Automatic conversion performed when there is no risk of data loss.
Manual conversion performed when there is a possibility of data loss.
1. Boxing converts ______.
2. Which conversion requires explicit casting?
3. Which keyword represents a Reference Type?
Create integer, double and character variables. Box them into object variables and unbox them back into their original data types.
