Understanding Generics—The Problem with (Un)Boxing Operations

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

Understanding Generics

© 2006 Andrew Troelsen

The Problem with (Un)Boxing Operations

Although boxing and unboxing are very convenient from a programmer’s point of view, this simplified approach to stack/heap memory transfer comes with the baggage of performance issues and a lack of type safety. To understand the performance issues, ponder the steps that must occur to box and unbox a simple integer:

1. A new object must be allocated on the managed heap.
2. The value of the stack-based data must be transferred into that memory location.
3. When unboxed, the value stored on the heap-based object must be transferred back to the stack.
4. The now unused object on the heap will (eventually) be garbage collected.

Although the current Main() method won’t cause a major bottleneck in terms of performance, you could certainly feel the impact if an ArrayList contained thousands of integers that are manipulated by your program on a somewhat regular basis.

Now consider the lack of type safety regarding unboxing operations. As you know, to unbox a value using the syntax of C#, you make use of the casting operator. However, the success or failure of a cast is not known until runtime. Therefore, if you attempt to unbox a value into the wrong data type, you receive an InvalidCastException:

static void Main(string[] args)
{
...
   // Ack! Runtime exception!
   Console.WriteLine("Value of your int: {0}", (short)myInts[0]);
   Console.ReadLine();
}

In an ideal world, the C# compiler would be able to resolve illegal unboxing operations at compile time, rather than at runtime. On a related note, in a really ideal world, we could store sets of value types in a container that did not require boxing in the first place. .NET 2.0 generics are the solution to each of these issues. However, before we dive into the details of generics, let’s see how programmers attempted to contend with these issues under .NET 1.x using strongly typed collections.


Previous_Page_.gif Next_Page_.gif

Personal tools