4/16/2008

Nullable types

Filed under: Developing .NET — Guus @ 11:07 am

Sometimes you discover something that is already existing for some time but you haven’t been aware of. I was studying for MCTS certification and I discovered the Nullable type. With this you can assign boolean of datetime objects the NULL value. It’s use full when you want to declare types but leave them unassigned (and check later).

This is the code sample:

   1:          //Normal notation
   2:          Nullable<bool> b = null;
   3:          
   4:          //Shorthand notation
   5:          bool? b2 = null;
   6:          
   7:          //Since it's nullable, you have 2 new value members: 
   8:          // HasValue and Value
   9:          if (b.HasValue) Console.WriteLine("b is {0}", b.Value);
  10:          else Console.WriteLine("b is not set");
  11:          
  12:          //Throws exception:
  13:          //Console.WriteLine("b is {0}", b.Value); 
  14:          
  15:          //Outputs 'b is '
  16:          Console.WriteLine("b is {0}", b ); 
  17:          
  18:          b = true;
  19:          //Outputs 'b is True'
  20:          Console.WriteLine("b is {0}", b ); 

This is available since .NET framework version 2.0

No Comments »

No comments yet.

RSS feed for comments on this post. | TrackBack URI

Leave a comment

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .