Pages

Sunday, April 26, 2009

Nullable types in C#

Nullable types in C# can represent all the values of an underlying type, and an additional null value. For example, nullable integer can have values like 10, 333, and null.

Nullable types have also a ?? -operator, that defines a default value that is returned when a nullable type is assigned to a non-nullable type. For example, you can use it to form a following operation: "a = b, unless b is null, in which case a=c". Or you can think it to be similar to SQL's NVL()-function.

Below is a code sample how to use nullable types and ??-operator.


    1 using System;
    2 
    3 namespace NullableTest
    4 {
    5   class Tester
    6   {
    7     static void Main(string[] args)
    8     {
    9       int? i = null;
   10       int? k = 5;
   11 
   12       // d = c, unless c is null, in which case d = -1.
   13       int a = i ?? -1;
   14 
   15       Console.WriteLine("Value of a is {0}", a);      
   16 
   17       // check if i has value
   18       if(i.HasValue)
   19         Console.WriteLine("Value of i is {0}", i.Value);
   20       else
   21         Console.WriteLine("i is null");
   22 
   23       // check if k has value
   24       if (k.HasValue)
   25         Console.WriteLine("Value of k is {0}", k.Value);
   26       else
   27         Console.WriteLine("k is null");
   28 
   29       Console.ReadLine();
   30     }
   31   }
   32 }

Further reading at MSDN:

Using Nullable Types (C# Programming Guide)

Nullable Types (C# Programming Guide)

No comments:

Post a Comment