How to Check for Null Values in C#

A while ago, almost two years, in fact, 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. It's a straightforward way, as long as the types are nullable, using .HasValue().

 

But what happens if we don't have nullable reference types enabled in our project? What options do we have to check if a variable is null or not?

  • Note: Obviously, what I'm going to explain also works with nullable reference types.

 

 

1 - Setting the Stage

I'm writing this post mainly because in the latest versions of C#, the way to check if an element is null has changed many times. This information can be very helpful if you're doing code reviews or want to expand your knowledge on the subject.

 

 

2 - Null Check in C# 6 and Earlier

In C# 6 (.NET Framework 4.6) and earlier, the only option we had was to use the equality operators == to check if a value is null or != to check if it's not 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 overloaded in code, so they might stop behaving as you expect them to:

public class PlaceholderClass
{
    public static bool operator ==(PlaceholderClass lhs, PlaceholderClass rhs)
    {
        return true;
    }

    public static bool operator !=(PlaceholderClass lhs, PlaceholderClass rhs)
    {
        return true;
    }
}


//Here is the code
PlaceholderClass obj = null;
if(obj != null)
{
    return "el if siempre devuelve verdadero";
}

As we see in the example, the equality operator always returns true, regardless of the real value. So, we can unintentionally cause unexpected behavior (although it's rare to overload these operators).

 

 

3 - Null Check in C# 7

For C# 7 (.NET Framework 4.7 and > .NET Standard 2.0), a new option became available: the is keyword, which lets us check whether an object is null or not.

string i = null;
if (i is null)
{
    return "El valor es null";
}

 

As you can see, it's easy to read and use to check that object.

However, there's a caveat: the way to check if an object is not null.

 

There are two options for this:

A - Use is object: if the variable you're checking is an object, it isn't null, so it's equivalent to checking if it's not null.

B - Negate the is with !(obj is null): the value inside the parenthesis is negated, so it becomes positive.

if (i is object)
{
    return "El valor no es null";
}

if (!(i is null))
{
    return "El valor no es null";
}

In my opinion, neither option is especially clear, in fact, they can be confusing.

 

This is not to mention 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" was introduced, along with a new way to check if an element is an object or not using the {} characters.

string i = null;
if (i is { })
{
    return "this cast to true";
}

 

 

5 - Null Check in C# 9

In C# 9 (.NET 5), this issue, or "nonsense", was fixed, and you can now check for null with the is not null syntax. It's easy, clear, and straightforward for anyone reading the code.

string i = null;
if (i is not null)
{
    return "El valor no es null";
}

As you can see, it is finally fast and simple.

 

 

6 - What Does the Future Hold?

Additionally, I found a proposal by Jared Parsons that I find very interesting. In summary, the language itself controls the null-check validation, and you could use the entry parameter of a method to ensure 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 feature is not included in the language.

 

Currently, if you enable <nullable>enable in your project and use Rider, and you add the exclamation mark, it automatically translates it to the following code:

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 support 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 any new ones (which they will) in the future, I'll update this post!

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café