Skip to main content

How to Compare a Nullable Value with Lifted Operators in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

ben >= 50 works even when ben is an int? that holds null: the answer is false, not an exception. C# calls these lifted operators, and their rules for null decide what your if statements do with a missing value.

The operators you use on int, such as == and >=, also work on int?. Microsoft's reference: A nullable value type T? supports the predefined unary and binary operators or any overloaded operators that a value type T supports. These operators, also known as lifted operators, return null if one or both operands are null. Otherwise, the operator uses the contained values of its operands to calculate the result.

Comparisons are the exception to "return null": they always return a bool. The reference: For the comparison operators <, >, <=, and >=, if one or both operands are null, the result is false. And: For the equality operator ==, if both operands are null, the result is true. If only one of the operands is null, the result is false. Otherwise, the contained values of operands are compared.

Syntax​

Syntax
bool <result> = <nullable> == <other>;
bool <result> = <nullable> != <other>;
bool <result> = <nullable> >= <other>;
<Type>? <sum> = <nullable> + <other>;
PartWhat it is
<nullable>A value of a nullable value type, such as an int?
<other>What to compare it with: a plain value such as 50, another nullable value, or null
==true when both sides hold the same value or both are null. false when only one side is null
!=The opposite of ==
>=, and <, >, <=Compares the values when both sides have one, and is false when either side is null
+, and the other arithmetic operatorsGives null when either side is null, so the result is a <Type>?

The Example​

A console app called NullableCompare has two test scores in int? variables: Ana scored 72, and Ben hasn't taken the test, so his score is null. It compares both scores with the pass mark of 50 and with 72.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n NullableCompare
cd NullableCompare
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NullableCompare/NullableCompare.csproj:
Determining projects to restore...
Restored /Users/you/source/NullableCompare/NullableCompare.csproj (in 39 ms).
Restore succeeded.

dotnet new console -n NullableCompare creates a folder named NullableCompare with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or NullableCompare.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the two scores:

Program.cs (the scores)
// Test scores out of 100: Ana scored 72, and Ben hasn't taken the test, so his score is null.
int? ana = 72;
int? ben = null;

ana holds 72, and ben holds null, which says that there's no score yet.

Then >= and <:

Program.cs (greater or less)
// >= compares the numbers. With null on one side, it's false.
Console.WriteLine($"ana >= 50: {ana >= 50}");
Console.WriteLine($"ben >= 50: {ben >= 50}");
Console.WriteLine($"ben < 50: {ben < 50}");

These are the same operators you use on int. On int? they compare the numbers when both sides have one, and with null on a side they return false instead of throwing.

Then ==:

Program.cs (equal)
// == compares the numbers too. null == null is true.
Console.WriteLine($"ana == 72: {ana == 72}");
Console.WriteLine($"ben == 72: {ben == 72}");
Console.WriteLine($"ben == null: {ben == null}");

ben == null asks with an operator whether there's no score.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
ana >= 50: True
ben >= 50: False
ben < 50: False
ana == 72: True
ben == 72: False
ben == null: True

macOS-style terminal window titled Terminal — NullableCompare showing dotnet run printing that ana >= 50 is True, that ben >= 50 and ben less than 50 are both False, that ana == 72 is True, that ben == 72 is False and that ben == null is True

ana >= 50 was True, as it would be with a plain int. For Ben, ben >= 50 and ben < 50 were both False: a null score is neither 50 or more nor less than 50. ana == 72 was True, ben == 72 was False, and ben == null was True.

The Complete File​

macOS-style code window titled Program.cs — NullableCompare showing int? ana set to 72 and int? ben set to null, then Console.WriteLine lines that print ana >= 50, ben >= 50, ben less than 50, ana == 72, ben == 72 and ben == null

Program.cs
// Test scores out of 100: Ana scored 72, and Ben hasn't taken the test, so his score is null.
int? ana = 72;
int? ben = null;

// >= compares the numbers. With null on one side, it's false.
Console.WriteLine($"ana >= 50: {ana >= 50}");
Console.WriteLine($"ben >= 50: {ben >= 50}");
Console.WriteLine($"ben < 50: {ben < 50}");

// == compares the numbers too. null == null is true.
Console.WriteLine($"ana == 72: {ana == 72}");
Console.WriteLine($"ben == 72: {ben == 72}");
Console.WriteLine($"ben == null: {ben == null}");

When null Lands in the else Branch​

Because both >= and < are false for null, an if with an else sends a missing value to the else branch. This check grades three scores, 72, 40 and null, first with a plain if and else, then with a test for null first:

Checking an if and else with null
int?[] scores = [72, 40, null];

// The mistake: else catches every score that isn't >= 50, null too.
foreach (int? score in scores)
{
string name = score.HasValue ? score.Value.ToString() : "null";
if (score >= 50)
Console.WriteLine($"{name}: passed");
else
Console.WriteLine($"{name}: failed");
}

// The fix: deal with null first.
foreach (int? score in scores)
{
string name = score.HasValue ? score.Value.ToString() : "null";
if (score is null)
Console.WriteLine($"{name}: not taken yet");
else if (score >= 50)
Console.WriteLine($"{name}: passed");
else
Console.WriteLine($"{name}: failed");
}
Output
72: passed
40: failed
null: failed
72: passed
40: failed
null: not taken yet

The name line only makes the label: the score, or the word null when there's none. In the first loop, the missing score printed null: failed, although nobody has taken that test. In the second, score is null is true when there's no score, so only real scores reach >=.

Common Mistakes​

MistakeWhat happensDo this instead
Reading false from >= as "below the limit"The null score went to the else branch and printed null: failedTest score is null first. The reference: Don't assume that because a particular comparison (for example, <=) returns false, the opposite comparison (>) returns true.
Comparing ben.Value >= 50 instead of ben >= 50The build warned warning CS8629: Nullable value type may be null., and the run threw InvalidOperationException: Nullable object must have a value.Compare ben itself, and let the lifted operator handle null
Putting ana + 5 into an interror CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)Keep the result in an int?: ana + 5 gave 77, and ben + 5 gave null

FAQ​

If null == null is true, is null >= null true too?​

No. With two int? variables, ben and cleo, that both hold null, ben == cleo printed True and ben >= cleo printed False. != is the opposite of ==: ben != 72 printed True, and ben != cleo printed False. The reference: For the inequality operator !=, if both operands are null, the result is false. If only one of the operands is null, the result is true.

Does a nullable enum work the same way?​

Yes. With Grade? grade = null, grade == Grade.A printed False and grade != Grade.A printed True. After grade = Grade.A, grade == Grade.A printed True.

Conclusion​

You can use ==, !=, <, >, <= and >= on nullable values directly: C# lifts them, so they return a bool with null instead of throwing. Every order comparison is false when a side is null, so wherever a missing value needs its own answer, test for null first.

Additional Resources​