Skip to main content
.NET Tips

Replace IF-Statements With Null Conditional Operators

Ever heard of the null conditional operator (?.) in C#? It helps make your code cleaner by safely accessing members or methods that might be null, returning null instead of throwing exceptions. A handy feature from C# 6.0! ✌️

Christian Schou

Ever heard about the null conditional operator? It is also referenced by instructors, software engineers and programmers in general as:

  • Null propagation operator.
  • Safe navigation operator.

It was a feature we first saw in C# 6.0 and I personally use it a lot! ✌️ It will allow you to make your code much more clean and concise, when you are working with data that might be null.

How Does It Work? 🤔

The null conditional operators is also known as a ?. in C# (question mark with a. dot). This notation is used to access a member or invoke a method that you know might return null when invoked. If the invoked object is null, it will return null instead of throwing a new exception, genius right?! 🔥

How To Do It? 💡

Let's get to the fun part and see how we can replace an IF-statement with this null conditional operator, in practice.

👎
The long way with an IF-statement.
if (invoice != null && invoice.Payment != null)
{
    invoice.Payment.AddFee(10);
}
👍
Using null conditional operator instead.
invoice?.Payment?.AddFee(10);

See the difference? 😅

Why Should I Do It? 🤓

I know a lot of programmers would think, yeah but I know my IF-statements and they work, why should I make the switch? Here are three reasons:

  1. Cleaner Code - You will reduce the need for if-statements, making your code shorter and easier to read. 🫶
  2. Prevents Errors - You will avoid the NullReferenceException by safely handling null objects. What's not to like? ✌️
  3. Consistent Null Checks - Standardizes null handling, improving code reliability and maintainability. Other engineers will love you! ❤️

Resources 🔗

Member access and null-conditional operators and expressions: - C# reference
C# operators that you use to access type members or null-conditionally access type members. These operators include the dot operator - `.`, indexers - `[`, `]`, `^` and `..`, and invocation - `(`, `)`.
Christian Schou