Boxing & Unboxing variable

Boxing & Unboxing variable

In C#, boxing is the process of converting a value type to an object type, which is a reference type. Unboxing, on the other hand, is the process of extracting the original value type from the boxed object.

Boxing can be useful in situations where a value type needs to be treated as an object type, such as when passing a value type as a parameter to a method that expects an object. For example, if you have an integer variable myInt and you want to pass it to a method that takes an object parameter, you can box the integer by assigning it to an object variable:

csharp

Copy code

int myInt = 42; object boxedInt = myInt; // boxing

Unboxing is the opposite process, where the original value type is extracted from the boxed object. This can be done using a type cast:

arduino

Copy code

int unboxedInt = (int) boxedInt; // unboxing

Note that unboxing can throw an InvalidCastException if the boxed object does not actually contain the expected value type.

It’s important to note that boxing and unboxing can have performance implications, as they involve creating and manipulating objects on the heap. In general, it’s best to avoid unnecessary boxing and unboxing operations whenever possible.

Linux and OSS
Distributions and linux evolution

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?