Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such a thing as a chained NULL check?

Tags:

c#

.net

I have the following ugly code:

if (msg == null || 
    msg.Content == null || 
    msg.Content.AccountMarketMessage == null || 
    msg.Content.AccountMarketMessage.Account == null ||
    msg.Content.AccountMarketMessage.Account.sObject == null) return;

Is there a way to chain check for null values in C#, so that I don't have to check each individual level?

like image 892
AngryHacker Avatar asked Apr 22 '14 22:04

AngryHacker


People also ask

WHAT IS null check?

A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something.

Is it good practice to check for null?

You will often want to say "if this is null, do this", and continue executing. Without the null check you won't get that chance, your whole call stack will be unwound and Unity will go on with the next Update() or whatever method it's going to call. Another is that exception handling is not free.

Where do you put a null check?

If you have implemented layering in your project, good place to do null checks are the layers that receives data externally.


2 Answers

One of the proposals in C# 6 would be to add a new Null Propogation operator.

This will (hopefully) allow you to write:

var obj = msg?.Content?.AccountMarketMessage?.Account?.sObject;
if (obj == null) return;

Unfortunately, there is nothing in the language at this point that handles this.

like image 114
Reed Copsey Avatar answered Sep 30 '22 12:09

Reed Copsey


There is not currently such a thing, but it may be coming to .NET very soon. There is a well-known User Voice thread on the subject. And as noted in this article, the Visual Studio team has recently announced that:

We are seriously considering this feature for C# and VB, and will be prototyping it in coming months.

Edit: and as noted in Reed Copsey's answer above, it is now a planned addition for C# 6. There are better details on the Codeplex pages he linked.

like image 23
Kimberly Avatar answered Sep 30 '22 14:09

Kimberly