Nullable Types - Null-Coalescing Operator ?? in C# .NET 2.0

Nullable types are instances of Nullable structure. This Nullable structure is a generic struct type in base class library. It behaves like value type when it has a value which means that boxing or unboxing occurs. However when it does not have a value, it is null instead of the value types default value, and boxind or unboxing does not occur.

There is a short notation for the generic Nullable structure. The ? operator is used for that purpose.

1
2
Nullable<int> i1;
int? i1;

These expressions evaluates the same CLR code.

Sometimes it is definitely needed to have the null value for the value types because sometimes the default value of the value types might be important, in case of database operations for example.

Also a new operator comes to the language. It’s named as coalescing operator, it is just a shorter form of some statements. The operator is ??. Here is the usage, and what it means for.

I think it makes code simpler but difficult to read. It is like using ? operator,instead of using if statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
string name = "test2";
string guessWhat = name ?? "NoName";






string guessWhat ;
if (name != null)
   guessWhat = name;
else
   guessWhat = "NoName";

This code snippet is exactly the same as the previous code snippet.

EXAMPLE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Collections.Generic;
using System.Text;

namespace Nullables
{
    class Program
    {
        static void Main(string[] args)
        {
            int? i1 = null;
            Nullable<int> i2 = null;
            int i3;

            if (i1 == null)
                Console.WriteLine("i1 is null");
            if (i2.HasValue)
                Console.WriteLine("i2 is not null");
            if (i3 == null)
                Console.WriteLine("i2 is null");

            string name = "test2";
            string guessWhat = name ?? "NoName";
            Console.WriteLine("name is test2 and value of guessWhat is " +guessWhat);
            name = null;
            guessWhat = name ?? "NoName";
            Console.WriteLine("name is null and value of guessWhat is "+ guessWhat);

            Console.ReadLine();
            
        }
    }
}

Here is the output of the code.

i1 is null i2 is null name is test2 and value of guessWhat is test2 name is null and value of guessWhat is NoName _