What is Boxing and Unboxing in C#?
What is Boxing and Unboxing in C#?
515
11-Jun-2024
Ashutosh Kumar Verma
11-Jun-2024C# Boxing and Unboxing
In C#, boxing and unboxing are two related concepts related to treating values and expressions. Understanding these concepts is important for effective memory management and optimal performance in .NET applications.
Boxing
Boxing is the process of converting a value type (such as int, float, struct, etc.) to a reference type (specifically, an object). Create an object on this heap and copy the value to this other object.
Syntax-
Here is, the integer
numis boxed into an objectobj.Unboxing
Unboxing is the opposite of boxing. This involves converting the boxed product back to its corresponding value. This requires an explicit cast and of course copying the value back to a variable value type.
Syntax-
Here is, The object
objunboxed into an integernumExample-
Output-
Key Points
Boxing
Unboxing
Performance Considerations
Boxing unboxing can have important business implications because,
Avoiding Boxing and Unboxing
Consider the following methods to avoid unnecessary boxing and unboxing,
By carefully understanding and managing boxing and unboxing, you can write more efficient and better-performing C# code.
Also, Read: How to sort object arrays by specific property in C#?