Boxing and Unboxing in C#

Boxing means the conversion of a value type on the stack to an object type on the heap. Any type of value or reference can be assigned to an object without explicit conversion. When the compiler finds a value type where it needs a reference type. then it creates an object box into which it places the value of the value type.

int x=20;
object o1=m; // create a box to hold x

Unboxing is the process of converting the object type back to the value type. Unboxing is an explicit conversion.
When performing unboxing, C# checks that the value type is actually stored in the object under conversion.

int x=20;
object o1=x;      // box x
float y=(int)o1;  // unbox o1 back to an int

Recommended Posts:

C#
    1. C# Features
    2. Difference Between C++ and C#
    3. Difference Between C# and Java
    4. .NET Framework
    5. Benefits of .NET
    6. C# Program Structure
    7. C# Command Line Arguments
    8. Console.ReadLine() and Console.WriteLine()
    9. C# Literals
    10. C# Data Types
    11. Scope of Variables in C#
    12. Boxing and Unboxing in C#
    13. C# Operators
    14. C# Type Casting