Share via


Boxing Nullable Types (C# Programming Guide) 

Objects based on nullable types are only boxed it the object is non-null. If HasValue is false, then, instead of boxing, the object reference is simply assigned to null. For example :

bool? b = null;
object o = b;
// Now o is null.

If the object is non-null -- if HasValue is true -- then boxing takes place, but only the underlying type that the nullable object is based upon is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable 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, like non-nullable boxed types, can be unboxed into nullable types, like this:

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

Remarks

The behavior of nullable types when boxed provides two advantages:

  • 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.
    }
    
  • Boxed nullable types fully support the functionality of the underlying type:

    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();
    

For more examples of nullable types, including boxing behavior, see Nullable Sample.

See Also

Concepts

C# Programming Guide
Nullable Types (C# Programming Guide)