[20th anniversary of .NET] Best of C# : null operators

In this series, I’d like to share with you my best experiences with .NET / C# and the best evolutions the .NET team brings us over the time.

Today I’d like to talk about null operators 🙂 C# provides 3 operatrs to make it easier to with with nulls :

  1. Null conditional operator
  2. Null coalescing operator
  3. Null coalescing assignment (new in C# 8)

You can find more details about these operators in this great book => Amazon.fr – C# 10 in a Nutshell: The Definitive Reference – Albahari, Joseph – Livres

Null-conditional operator

The ?. operator is also called the Elvis operator and as originally introduced in C# 6. It allows you to call methods and access members like the . operator except that if the left operand is null, the expression is evaluate to null without throwing the killer exception ‘NullReferenceException‘.

string s = null;
string sUpper = sb?.ToUpper(); // sUpper is null

The only condition is that the final expression/assignment is capable of accepting a null (exit all value type) :

string s = null;
int lengthS = s?.Length; // Won't compile

Then use a Nullable :

string s = null;
int? lengthS = s?.Length; // Ok

Null-coalescing operator

The very useful ?? operator tells to return the value of the left operand if it’s not null, else return the specify value (right operand – example : default value)

string s = null;
string sDefault = s ?? "My default value"; // sDefault is "My default value"

Another good use of this operator is to check an assignment and rise an exception if null (example in ASP.NET controller or anywhere else) :

_companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));

Null-coalescing assignment (C# 8)

The ??= operator assigns a variable only if it’s not null. So it’s a sugar syntax to replace this :

if (s != null) s = "Hello world";

with this :

s ??= "Hello world";

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.