DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

C#: What is Boxing?

My friend asked me about C# boxing at the end of last year, and I promised to explain in a blog article this year. So, this is the article for him.

Value Type and Reference Type

Before I explain the C# boxing, I need to explain that C# has two categories of types.

  • Value Types
  • Reference Types

Value Types

Value Types is a type that an instance of the type contains the value. If I pass the value as a method argument or assign it to a new variable, the copy of the instance is created.

Following code demonstrates that the x and y values are independent objects, because the instance of x is copied to the y value as the new instance.

int x = 1;
int y = x;
y += 1;
Console.WriteLine($"x: {x}");
Console.WriteLine($"y: {y}");
Enter fullscreen mode Exit fullscreen mode
x: 1
y: 2
Enter fullscreen mode Exit fullscreen mode

The instances of Value types are stored in the stack area.

Reference Types

Reference Types is a type that an instance of the type contains the refence to the object. If I pass the value as a method argument or assign it to a new variable, both variable points to the same object.

Following code demonstrates that the x and y variables are pointing to the same object in memory after assigning it.

char[] x = { 't', 'e', 's', 't' };
Console.WriteLine($"x: {new string(x)}");
char[] y = x;
y[0] = 'n';
Console.WriteLine($"x: {new string(x)}");
Console.WriteLine($"y: {new string(y)}");
Enter fullscreen mode Exit fullscreen mode
x: test
x: nest
y: nest
Enter fullscreen mode Exit fullscreen mode

The instances of Reference types are stored in managed heap area.

Boxing and Unboxing

Boxing is a process to move the value type instance from the stack to the managed heap by converting it to an object type.

Unboxing is a process to extract the value type instance from the managed heap to the stack.

How it happens

Boxing happens when we assign a value type instance to System.Object. Unboxing happens when we convert a reference type instance to a value type.

int x = 1; // boxing 
object xobj = x;
int y = (int)xobj; // unboxing
Enter fullscreen mode Exit fullscreen mode

Open the compiled dll from ILDASM tool, then we can clearly see it.

ILDASM

What's the issue?

According to Microsoft official documentation, it has a performance penalty: Performance: Boxing and Unboxing

The ArrayList document also explains about it.

Summary

It may be important to know how C# works under the hood, but there is not much we can do. We simply need to aware of this behavior and follow the best practice to code. I hope this article helps my colleague.

Top comments (0)