Null checks and if clause evaluation order

Posted on 2/26/2014 @ 8:57 PM in #Vanilla .NET by | Feedback | 1198 views

Null checks are tough to get right.

Here is the thing, sometimes you are passed in a variable that is an array or collection, and it could be null, or it could be initialized with zero objects in it.

For instance, the code below,

   1:  string[] args1 = null;
   2:  if (args1.Length == 0 || args1 == null)
   3:  {
   4:   // do something
   5:  }

 

The above code will throw an exception because C# will evaluate left to right. So you are possibly checking args1.Length – and you may get a NullReferenceException.

How to fix the above? Easy, just reverse the null check at the very beginning, like this -

   1:  string[] args1 = null;
   2:  if (args1 == null || args1.Length == 0)
   3:  {
   4:    // do something
   5:  }

Sound off but keep it civil:

Older comments..