C# boxing and unboxing
Within the C# type system, three distinct types are present: value types, reference types, and pointer types. C# provides the capability to convert value types to reference types through the process known as boxing, as well as reverting reference types back to value types, which is referred to as unboxing. Boxing entails encapsulating a value type within a reference type, enabling it to be treated as an object. Conversely, unboxing involves extracting the original value type from the boxed object. These operations of boxing and unboxing serve as fundamental mechanisms for seamless conversion and interoperability between value types and reference types within the C# programming language.
Boxing
Boxing is the process of converting a value type to a reference type by wrapping it in an object. When a value type is boxed, it is allocated on the heap instead of the stack, and a reference to the boxed object is created. This enables the value type to be treated as an object and used in scenarios where only reference types are accepted.
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 = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.
UnBoxing
Unboxing is the reverse operation of boxing. It extracts the value type from the boxed object and assigns it back to a value type variable. It involves casting the boxed object back to its original value type.
The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.
Boxing and UnBoxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed , also the cast required for UnBoxing is also expensive computationally.
Full Source C#It is important to note that unboxing can only be performed successfully if the boxed object is of the correct value type. Attempting to unbox an object into an incompatible value type can result in an InvalidCastException.
Conclusion
Boxing and unboxing operations can have a performance impact since they involve memory allocation and type conversions. It is generally recommended to use them sparingly and be mindful of their potential implications in performance-critical sections of code.
- How to CultureInfo in C#
- How do I solve System.InvalidCastException?
- Difference between readonly and const keyword
- DateTime Format In C#
- Difference Between Task and Thread
- Object reference not set to an instance of an object
- How to Convert Char to String in C#
- How to Convert Char Array to String in C#
- How to convert int to string in C#?