Unicorn with delicious cookie
Nous utilisons des cookies pour améliorer votre expérience de navigation. En savoir plus
Accepter
to the top
>
>
>
Boxing and Unboxing in C#

Boxing and Unboxing in C#

21 Aoû 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

S'abonner

Comments (0)

close comment form
close form

Remplissez le formulaire ci‑dessous en 2 étapes simples :

Vos coordonnées :

Étape 1
Félicitations ! Voici votre code promo !

Type de licence souhaité :

Étape 2
Team license
Enterprise licence
** En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité
close form
Demandez des tarifs
Nouvelle licence
Renouvellement de licence
--Sélectionnez la devise--
USD
EUR
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
La licence PVS‑Studio gratuit pour les spécialistes Microsoft MVP
close form
Pour obtenir la licence de votre projet open source, s’il vous plait rempliez ce formulaire
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
I want to join the test
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
check circle
Votre message a été envoyé.

Nous vous répondrons à


Si l'e-mail n'apparaît pas dans votre boîte de réception, recherchez-le dans l'un des dossiers suivants:

  • Promotion
  • Notifications
  • Spam