Different ways to check a null object

C# provides various ways to check for a null object.

Let’s create a class to test;

public class UserObject
{
    public int Id { get; set; }
    public string? Name { get; set; }
}

The most conventional way to check for null is by equating the object with null.

UserObject userObject = null;
//Conventional way to check for null
if (userObject == null)
{
    userObject = new UserObject();
    Console.WriteLine("userObject null - handled using conventional manner");
}

if (userObject != null)
{
    Console.WriteLine("userObject not null - handled using conventional manner");
}

C#7 introduced a new way to write the above code in a more readable way by using the is keyword.

//C#7 introduces a new way 
userObject = null;
if (userObject is null)
{
    userObject = new UserObject();
    Console.WriteLine("userObject null - handled using c#7");
}

The same code can be written using null-coalescing operator.

//we can write the same code using null-coalescing operator
userObject = null;
userObject = userObject ?? new UserObject();
Console.WriteLine("userObject null - handled using null-coalescing operator");

C#9 introduced a new way to write the above code in a more readable way by using the is not keyword.

//C#9 introduces a new way 
if (userObject is not null)
{
    userObject = new UserObject();
    Console.WriteLine("userObject not null - handled using c#9");
}

Hope, this helps.

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect