C# Nullable Types
Nullable Types
An int variable always has a value. But sometimes a value is unknown. For example, a new player in a game has no score yet.
You could use 0 for "no score". But 0 is also a real score: the player played and got zero points.
In C#, null means "no value". But a normal int cannot be null:
Example
int score = null;
Console.WriteLine(score);
The compiler shows an error like this:
prog.cs(9,19): error CS0037: Cannot convert null to `int' because it is a value type
To allow null, add a question mark ? after the type. This is called a nullable type:
Example
int? score = null;
Console.WriteLine(score == null); // True
score = 25;
Console.WriteLine(score); // 25
int? can store any int value, or null. You can add ? to other types too, like double? and bool?.
HasValue and Value
A nullable variable has two useful properties:
HasValueistrueif the variable has a value, andfalseif it isnullValuegives you the value
In this example, the ShowScore() method uses HasValue to check if the player has a score:
Example
static void ShowScore(int? score)
{
if (score.HasValue)
{
Console.WriteLine("Score: " + score.Value);
}
else
{
Console.WriteLine("No score yet");
}
}
static void Main(string[] args)
{
ShowScore(25);
ShowScore(null);
}
Give a Default Value With ??
Often you want a normal value to work with, even when the variable is null.
The ?? operator gives a default value. It uses the value on the left if it is not null. If it is null, it uses the value on the right:
Example
int? score = null;
int points = score ?? 0;
Console.WriteLine(points); // 0
score = 25;
points = score ?? 0;
Console.WriteLine(points); // 25
The first time, score is null, so points gets 0. The second time, points gets the score, 25.
The GetValueOrDefault() method works in a similar way. With empty parentheses, it uses 0 for an int. You can also write the default value inside the parentheses:
Example
int? score = null;
Console.WriteLine(score.GetValueOrDefault()); // 0
Console.WriteLine(score.GetValueOrDefault(10)); // 10
Null Strings
A string can also be null, without a question mark. For example, a player may not have chosen a name yet.
The ?? operator works with strings too:
Example
string name = null;
Console.WriteLine(name ?? "Guest"); // Guest
name = "Liam";
Console.WriteLine(name ?? "Guest"); // Liam
If you use a property of a null string, like name.Length, the program stops with an error (a NullReferenceException).
To avoid the error, write ?. instead of a dot. If name is null, name?.Length gives null instead of an error:
Example
string name = null;
int? length = name?.Length;
Console.WriteLine(length.HasValue); // False
name = "Liam";
length = name?.Length;
Console.WriteLine(length.Value); // 4
The result of name?.Length can be null, so it is stored in an int?. To get a normal int, combine ?. with ??:
Example
string name = null;
int length = name?.Length ?? 0;
Console.WriteLine(length); // 0