Day 2: Avoid Null Exceptions with C# operators

Leslie Ramírez
2 min readDec 7, 2021

--

Hi everyone, let’s get started our coding winter with an important topic, how to work with null values in C#.

One of the more typical exceptions we can find in a strongly-typed programming language is a Null reference Exceptions. C# provides three operators to make it easier to work with null: the null-coalescing operator, the null-coalescing assignment operator, and the null-conditional operator.

But let’s see first what it means Nullable value types, by definition references types can represent a non-existing value. That’s we can do something like this:

We can solve this problem by using a special construct called nullable. Other cases of the method we have to deal with nulls are the use of:

Null-Coalescing Operator

?? returns the value of its left-hand if it isn’t null; it evaluates the right-hand operand and returns its result.

Null-Coalescing Assignment Operator

??= This is available from C# 8.0 and later, operates in the way “if the left-hand evaluates to null assigns the value of the right hand”

When it’s useful to use this operator:

  • When you work with nullable value types and need to provide a value of an underlying value type, use the ?? operator to specify the value to provide in case a nullable type value is null.

Ways to avoid Null Reference Exception:

  1. Don’t forget to instantiate a reference type.
  2. Remember if you get a null return value from a method, and then call a method on the returned type by consequence the runtime throws a NullReferenceException exception.

In this short post, I just wanted to show you the options you have to work with nulls and avoid Null reference Exceptions. If you want to go deep into these topics I recommend you to read this:

C# operators and expressions — C# reference | Microsoft Docs

See you on Thursday again :D

--

--

Leslie Ramírez

I am Microsoft MVP in the award category: Developers technologies, a professional with several years in software development specifically in .NET technology.