[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";

Add data attributes in Razor view with HTML helper method

With HTML 5 and JS frameworks heavily using data attributes within HTML tags, Razor views could cause you a headache without this little tip for attributes.

For example Data attributes have a syntax like « data-* ». If you add the hyphen within the name of an attribute in your anonymous class, Razor engine will interprets it simply as a minus sign … and won’t compile !

To add a Data attribute (or any other attribute with a hyphen within the name) within an HTML helper, you should replace the hyphen with an underscore. Hence, Razor engine will understand this and converts it to a hyphen in the HTML output.

@Html.DropDownList("Country", ViewData["Countries"] as SelectList, new { @class = "selectpicker", data_style = "btn-form-control" })

The HTML output will be:

<select id=”Country” name=”Country” class="selectpicker" data-style=”btn-form-control” />