C# Nullable Types
C# Single Question Mark ? and Double Question Mark ??
The ?
single question mark is used to assign null values to data types like int, double, bool that cannot be directly assigned null. It indicates that the data type is a Nullable type.
int? i = 3;
This is equivalent to:
Nullable<int> i = new Nullable<int>(3);
int i; // Default value is 0
int? ii; // Default value is null
The ??
double question mark is used to return a specified value if a variable is null.
Let's explain this in detail.
C# Nullable Types
C# provides a special data type, nullable type, which can represent the normal range of values for its underlying value type plus a null value.
For example, Nullable< Int32 >, read as "nullable Int32", can be assigned any value from -2,147,483,648 to 2,147,483,647, or a null value. Similarly, a Nullable< bool > variable can be assigned true, false, or null.
This is particularly useful when dealing with databases and other data types that may contain elements that are not assigned a value. For example, a boolean field in a database can store true or false, or it may be undefined.
The syntax to declare a nullable type is as follows:
< data_type> ? <variable_name> = null;
The following example demonstrates the use of nullable data types:
Example
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolval = new bool?();
// Display values
Console.WriteLine("Displaying nullable types: {0}, {1}, {2}, {3}",
num1, num2, num3, num4);
Console.WriteLine("A nullable boolean value: {0}", boolval);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Displaying nullable types: , 45, , 3.14157
A nullable boolean value:
Null Coalescing Operator ( ?? )
The null coalescing operator is used to define a default value for nullable types and reference types. It provides a preset value in case the value of the nullable type is null. The null coalescing operator implicitly converts the operand type to the type of the other operand, which can be either nullable or non-nullable.
If the first operand is null, the operator returns the value of the second operand; otherwise, it returns the value of the first operand. The following example demonstrates this:
Example
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34; // num1 if null then return 5.34
Console.WriteLine("Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine("Value of num3: {0}", num3);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Value of num3: 5.34
Value of num3: 3.14157