VC++ MVP 2006, C# MVP 2007 Ravi Bhavnani's .NET bits
A compendium of scribblings, hacks, and things .NET

Linkworthy
  • The CodeProject
  • CodePlex
  • Channel 9
  • The Lab with Leo Laporte
  •  
    True, false, or undefined?
    Nullable types to the rescue
    by Ravi Bhavnani, 15 Oct 2007
    Home  All articles

    In a past life I developed an MFC app that was a configuration editor for a complex search engine.  The engine's configuration, expressed as a large graph of objects, was serialized to persistent storage as a collection of XML files.

    Reading in the files into the data model was easy enough, but I soon found myself having to deal with missing (i.e. optional) elements and attributes.  I resorted to creating wrapper classes for these potentially absent entities (expressed as bools, ints and CStrings).  The wrapper classes had an extra bit that indicated whether the object had a value - i.e. was defined.  Something along the lines of this:

      1   class DefinedBool
      2   {
      3     protected:
      4       // The object's "defined" state.
      5       bool  m_bDefined;
      6   
      7       // The object's value.
      8       bool m_bValue;
      9   
     10       ...
     11   };

    If I'd developed the app several years later, I'd have used .NET, and specifically .NET 2.0, which brings with it the concept of a "nullable" value type.  The entire DefinedBool class shown above can be replaced by the following declaration:

      bool? _someBoolAttribute;

    The question mark following the data type indicates that the variable can can have a null value.  This declaration is actually shorthand for a nullable instance of a bool which would be defined as:

      System.Nullable<bool> _someBoolAttribute;

    We work with _someBoolAttribute by using its HasValue and Value properties, like so:

      1   // Print value of someBoolAttribute
      2   if (_someBoolAttribute.HasValue)
      3       System.Console.Writeline ("someBoolAttribute is {0}",
      4                                  someBoolAttribute.Value.ToString());
      5   else
      6       System.Console.Writeline ("someBoolAttribute undefined");

    And there you have it - a simple and elegant feature that allows us to identify a value type's potentially undefined state.

     

    Most of the drivel at this site is copyright © Ravi Bhavnani.
    Questions or comments?  Send mail to ravib@ravib.com