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();
}
}
}
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();
}
}
}