Friday, April 21, 2023

What is boxing and unboxing in C# ?

In C#, boxing and unboxing allow you to convert a value type to a reference type and vice versa. Here's an example of boxing and unboxing.
// Boxing example

int value = 10;

object obj = value; // Boxing - converting value type to reference type
// Unboxing example

object obj2 = 20;

int value2 = (int)obj2; // Unboxing - converting reference type to value type
In the above example, the 'value' variable is of type 'int', which is a value type. When we assign 'value' to 'obj', we are boxing the 'int' value into an 'object' reference type. Similarly, in the unboxing example, we are converting an 'object' reference type to an 'int' value type using a cast operator '(int)'.

Boxing and unboxing can be useful in certain scenarios, but they can also be inefficient in terms of performance, especially when used frequently. It is recommended to avoid unnecessary boxing and unboxing and use generic types instead.

No comments:

Post a Comment