Our website uses cookies to enhance your browsing experience.
Accept
to the top
close form

Fill out the form in 2 simple steps below:

Your contact information:

Step 1
Congratulations! This is your promo code!

Desired license type:

Step 2
Team license
Enterprise license
** By clicking this button you agree to our Privacy Policy statement
close form
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
* By clicking this button you agree to our Privacy Policy statement

close form
Free PVS‑Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

close form
To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

close form
I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

close form
check circle
Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
Boxing and Unboxing in C#

Boxing and Unboxing in C#

Aug 21 2023

Boxing and unboxing allow developers to convert value types to reference types and vice versa. These operations can reduce performance due to additional calculations, such as allocating memory for a new object and copying data.

Boxing

Boxing occurs when a value type is converted to the System.Object, System.Enum, System.ValueType, or interface type. This operation can be explicit or implicit:

int a = 10;
object b = a;          // Implicit boxing
object c = (object)a;  // Explicit boxing

Implicit boxing occurs when we use a value-type variable where a reference type is expected. Let's look at the examples of such operations:

  • calling a method with reference-type parameters and value-type arguments;
  • calling methods of the base reference type of value-type instances;
  • declaring a reference-type variable with initialization of a value-type instance.

You can find some detailed examples below.

Example 1

struct Point : IComparable<Point>
{
  .... 
  public int CompareTo(Point point) { .... }
}

static void 
ProcessComparableItems<T>(IComparable<T> lhs,
                          IComparable<T> rhs)
{ .... }

static int Calculate(....)
{
  var firstPoint = new Point(....);
  var secondPoint = new Point(....);
  ProcessComparableItems(firstPoint, secondPoint);
  ....
}

The ProcessComparableItems method handles two IComparable<T> parameters. At the same time, the Point structure implements this interface. However, if we call the ProcessComparableItems method with arguments of the Point type, each of them is boxed:

// ProcessComparableItems(firstPoint, secondPoint);
IL_0039: ldloc.0
IL_003a: box BoxingTest.Program/Point  // <=
IL_003f: ldloc.1
IL_0040: box BoxingTest.Program/Point  // <=
IL_0045: call void 
  BoxingTest.Program::ProcessComparableItems
    <valuetype BoxingTest.Program/Point>(....)
....

Example 2

var dateTime = new DateTime(....);
Type typeInfo = dateTime.GetType();

dateTime is a variable of the (DateType) value type. The GetType method of dateTime, defined in the System.Object type, is called. To call the method, we need to perform boxing of the dateTime object:

// Type typeInfo = dateTime.GetType();
IL_0014: ldloc.0
IL_0015: box [System.Runtime]System.DateTime // <=
IL_001a: call instance class
  [System.Runtime]System.Type
  [System.Runtime]System.Object::GetType()
....

Unboxing

Unboxing is the conversion of a boxed reference type back to a value type. Unboxing has some peculiarities:

  • Unboxing must be done to exactly the same data type that was boxed. Unboxing to an incompatible value type causes an InvalidCastException.
  • Attempting to unbox a null reference causes a NullReferenceException.

Example:

double a = 1;
object b = a;
int c = (int)b;

Unboxing a variable to an incompatible value type causes InvalidCastException. Here is the fixed code:

int c = (int)(double)b;

Additional Resources

Popular related articles


Comments (0)

Next comments next comments
close comment form