A while ago—in fact, almost two years ago—I wrote a post about nullable types in C#.
In that video, I explained how nullable types work using the ?
character and how to check if that variable is null or not—a simple way, as long as the types are nullable
by using .HasValue()
.
But what if we don’t have nullable reference types enabled in our project? What options are there to validate whether a variable is null or not?
- Note: obviously, what I’m going to explain also works with nullable reference types.
Index
1 - For context
This post exists mainly because in recent versions of C# we’ve seen how the way to check if an element is null or not has changed multiple times. So, knowing this information can be quite useful if you’re doing code reviews or want to expand your knowledge on the topic.
2 - Null check in C# 6 and earlier
For versions up to C# 6 (.NET Framework 4.6), the only option we have is to use the equality operators ==
to check if a value is null, or !=
to check if the value is different from null.
int i = null;if(i == null){ return "el valor de I es null, y eso no puede ser";}if (i != null){ return "el valor No es null";}
The problem comes when you discover that both ==
and !=
can be overwritten in your code, and as a result, they’d stop doing what we actually want:
public class PlaceholderClass{ public static bool operator ==(PlaceholderClass lhs, PlaceholderClass rhs) { return true; } public static bool operator !=(PlaceholderClass lhs, PlaceholderClass rhs) { return true; }}//Here’s the codePlaceholderClass obj = null;if(obj != null){ return "el if siempre devuelve verdadero";}
As we can see in the example, the equality operator always returns true—it doesn’t matter what the real value is. So we might unintentionally cause unexpected behavior (although it’s quite rare to override the operators).
3 - Null check in C# 7
For C# 7 (.NET Framework 4.7 and later, or .NET Standard 2.0), we have a new option available: the is
keyword, which lets us check if an object is null or not.
string i = null;if (i is null){ return "El valor es null";}
There you can see it’s straightforward and easy to read.
However, there’s a problem when checking if an object is not null.
There are two options for that:
A - Use is object
. If the variable you’re checking is an object, it’s not null, so this is the same as checking that it is not null.
B - Negate the is
with !(obj is null)
. The value inside the parenthesis becomes false when it’s not null; negate it and it’s true.
if (i is object){ return "El valor no es null";}if (!(i is null)){ return "El valor no es null";}
In my opinion, neither of these is clear enough, and can actually be confusing.
This is not to forget the null-coalescing
operator, which also lets us control if an object is null or not:
Obj result = aquiElObeto ?? new Obj();
4 - Null check in C# 8
With the arrival of C# 8 (.NET Standard 2.1 and .NET Core 3.1+), “pattern matching” came along with it and brought a new way to check if an element is an object or not, using {}
.
string i = null;if (i is { }){ return "this cast to true";}
5 - Null check in C# 9
In C# 9 (.NET 5), that oddity was fixed, and now we can perform null checks with is not null
, which is clear, easy, and simple for anyone who reads the code.
string i = null;if (i is not null){ return "El valor no es null";}
As you can see, now it’s fast and easy—finally.
6 - What does the future hold?
Additionally, I’ve found a proposal by Jared Parsons that I find quite interesting. In short, it would be the language that enforces null-check validation: we can use the input parameter of a method and check that it’s not null by using the !
operator.
public string Execute(PlaceholderClass test!){ //code}
The program will throw an exception ArgumentNullException
if the parameter is null.
You can find the proposal here: link.
But for now, this functionality is not included in the language.
Currently, if we enable <nullable>enable
in our project, and we’re using Rider, and we indicate the exclamation mark, it automatically translates it to:
public string Execute(PlaceholderClass test){ if (test == null) throw new ArgumentNullException(nameof(test)); //rest of the code}
This makes me think that at least Jetbrains is preparing to include this feature.
Conclusion
That’s it for this post. We’ve seen how to check if a variable is null or not in different versions of .NET.
And if they add something new in the future (which they will), I’ll keep this post up to date.
If there is any problem you can add a comment bellow or contact me in the website's contact form