Monday, March 29, 2010

What is boxing and unboxing?

Boxing converts a value to a reference type, and unboxing converts a reference type to a value type.

The .NET code samples below show boxing and unboxing.

Boxing Example
' VB
Dim i As Integer = 123
Dim o As Object = CType(i, Object)

// C#
int i = 123;
object o = (object)  i;


Unboxing Example
' VB
Dim o As Object = 123
Dim i As Integer = CType(o, Integer)

// C#
object o = 123;
int i = (int)  o;


Additional Resources
Boxing and Unboxing (ASP Alliance)

No comments:

Post a Comment