Jaydeep Patil

Jaydeep Patil

  • 115
  • 15.8k
  • 2.1m

Boxing and Unboxing

Apr 20 2022 4:39 PM

In .NET Core sometimes we want to convert data from one data type to another and vice versa at that time we will use boxing and unboxing technique.

 

Boxing -

 

Boxing is use when we want to convert value type data into the reference type called boxing. Ex-

 

int i = 123;
object o = i;

 

Unboxing -

 

Unboxing is use when we want to convert reference type data into value type called unboxing. Ex- 

 

object o = 123;
int i = (int)o;

 

In following scenarios we will use this boxing and unboxing.

 

- Boxing/unboxing occurs when a value type (like a struct, int, long) is passed somewhere that accepts a reference type - such as object.

 

- This occurs when you explicitly create a method that takes parameters of type object that will be passed value types.

 

public void string Decorate( object a ) // passing a value type results in boxing
{
return a.ToString() + " Some other value";
}

 

Note - Boxing is an expensive process, since it copies an object from a stack to a heap which requires a number of processor as well as space on the heap and other disadvantage of using boxing is that the same object appears at two different places in memory which can have contradictory state.

 

Add something If you want to know about it in the below comment box


Answers (2)