Compartilhar via


Boxing Nullable Types (C# Programming Guide)

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:

      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