Nullable Types in C#

nullable data types in C# are similar to the other data types except they can store null values apart from the predefined data type. For instance if you create a nullable integer variable, you can store an integer as well as a null value in that variable. Normal variables can be specified as nullable by simply appending a question after the type specification. Consider following example to understand the concept.

using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {
            int? var1 = null;
            int? var2 = 10;
            int? var3 = null;
            bool? on = null;

            Console.WriteLine("The int variable var1, var2 and var 3 contains {0}, {1} and {2}", var1, var2, var3 );
            Console.WriteLine("The bool variable on contains " + on);
            Console.ReadKey();
        }
    }
}

Download the code
In the above code, three nullable integer type variables have been declared i.e. var1, var2 and var3. The first and third variable stores null while the second one stores 10. Now, if these variables are printed on screen, you will see that nothing will be printed in their place. Similarly, boolean variable ‘on’ has also been assigned a null value which when printed on console will not be displayed.

Null Coalescing Operator

In addition to nullable types, C# contains Null coalescing operator which is used to store some other value in the operand if the first value null. Coalescing operator is denoted by double question marks. Have a look at the following example.

using System;
namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {
            int? var1 = null;
            int? var2 = 10;
            int? var3 = null;

            var3 = var1 ?? 15;
            Console.WriteLine("The variable var3: "+var3);

            var3 = var2 ?? 20;
            Console.WriteLine("The variable var3: " + var3);

            Console.ReadKey();
        }
    }
}

Download the code
In above example again var1 and var3 contains null while var2 contains 10. The value of var1 is stored in var3 with the addition of coalescing operator which says that if var1 contains null, store value 15 in var3. Var3 is then displayed on console which shall display 15. Next, value of var2 is stored in var3 and this time coalescing operator stores 10 in var2 if var2 contains null. But since var2 contains 10, therefore 10 will be stored in var3 and will be consequently displayed on console.

<<< Enumerations in C#Strings in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .