You are on page 1of 3

Boxing Nullable Types (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/ms228597

Boxing Nullable Types (C# Programming Guide)


Visual Studio 2010 1 out of 1 rated this helpful - Rate this topic Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing. For example:

bool? b = null; object o = b; // Now o is null. If the object is non-null -- if HasValue is true -- then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable<T> that wraps the value type. For example:

bool? b = false; int? i = 44; object bBoxed = b; // bBoxed contains a boxed bool. object iBoxed = i; // iBoxed contains a boxed int. The two boxed objects are identical to those created by boxing non-nullable types. And, just like non-nullable boxed types, they can be unboxed into nullable types, as in the following example:

bool? b2 = (bool?)bBoxed; int? i2 = (int?)iBoxed;

Remarks
The behavior of nullable types when boxed provides two advantages: 1. Nullable objects and their boxed counterpart can be tested for null:

bool? b = null; object boxedB = b; if (b == null) { // True. } if (boxedB == null) { // Also true. } 2. Boxed nullable types fully support the functionality of the underlying type:

1 of 3

5/25/2012 11:48 AM

Boxing Nullable Types (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/ms228597

double? d = 44.4; object iBoxed = d; // Access IConvertible interface implemented by double. IConvertible ic = (IConvertible)iBoxed; int i = ic.ToInt32(null); string str = ic.ToString();

See Also
Tasks How to: Identify a Nullable Type (C# Programming Guide) Reference Nullable Types (C# Programming Guide) Concepts C# Programming Guide

Did you find this helpful?

Yes

No

Community Content
Problem with boxing a boolean nullable
In the next code boxing alters the behaviour of the if-else 100%. Instead of executing the else-branch, the if-branch is executed:
'Without boxing. Dim var1 As Boolean? = New Boolean? If Not var1 Then Stop Else Stop 'THIS LINE IS EXECUTED End If 'With boxing. Dim var2 As Object = New Boolean? If Not var2 Then Stop 'THIS LINE IS EXECUTED Else Stop End If

12/6/2011 MagiesH

2 of 3

5/25/2012 11:48 AM

Boxing Nullable Types (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/ms228597

2012 Microsoft. All rights reserved.

3 of 3

5/25/2012 11:48 AM

You might also like