How Null Checks Are Changed In C#

In this article, we are going learn about what and how NULL checking in C# improved over these years in different versions.

NULL checks in C# v.6

Let’s starts with C# v.6 which is the last version before the bigger changes started happening. Basically, all we’ll do to check whether the variable is null or not as follows,

Var value = new Random().Next(10) > 5 ? “not null” : null;
If(value == null) {
    Console.WriteLine(“value is null.”);
}
If(value != null) {
    Console.WriteLine(“value is not null.”);
}

These are very straightforward there’s nothing really to do much. We also use NULL propagation method for NULL check.

If(value?.Name == null) {
    Console.WriteLine(“value is null.”);
}

The question mark symbol which used in if condition, which means that it’ll check whether value is NULL, if not then it’ll check whether Name is null.

Also, we can also do Null using Null Coalescing operator,

Var test = value ?? “value is null”;

It’ll check if the value is Null, if Null it’ll return “value is null” string.

NULL checks in C# v.7

C# v.7 will support all v.6 Null check methods, in v.7 it spiced things up a bit with pattern matching,

If(value is null) {
    Console.WriteLine(“value is null.”);
}

Above method is pattern matching feature that was introduced in C# v.7. We may also think like we can also do “is not null” . But we do the opposite to check no null as follows,

If(!(value is null)) {
    Console.WriteLine(“value is null.”);
}

We must wrap “value is null” into brackets like above, to do the not Null check operation.

We have another option to Null check,

If(value is object) {
    Console.WriteLine(“value is not null.”);
}

This is basically a value is not null check operation.

NULL checks in C# v.8

C# v.8 will support all the v.6 and v.7 Null check methods, but in v.8 Microsoft improved the “is object” Null check as follows,

If(value is {}) {
    Console.WriteLine(“value is not null.”);
}

We can use these curly braces to check whether the value is not Null.

Another interesting Null check feature that was added in C# v.8 was the Null Coalescing assignment, which is basically the Null Coalescing with an equal’s operator.

Value ??= “assign string or int or any object”;

This basically will check, if value is null then assign to whatever we mentioned after the assignment operator.

NULL checks in C# v.9

As we already seen above in C# v.7, there is one way of to do Null check,

If(!(value is null)) {
    Console.WriteLine(“value is null.”);
}

This above maybe not be perfectly readable. In C# v.9 this feature is improved much better with readable syntax, like follows,

If (value is not null)
{
    Console.WriteLine(“value is null.”);
}

Other then this v.9 C# will support all other versions Null check methods.

Conclusion

So far, we have seen some new features to do the Null check in various C# versions. Thanks for reading, have a good day


Recommended Free Ebook
Similar Articles