Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check if a variable is null or empty

Tags:

c#

null

I have the following code which a colleague of mine told me is incorrect and will crash if my variable is null:

List<FSKUser> users = null;

if (users == null || users.Count() == 0)
{
   return false;
}

Obviously the =null is just for testing purpose. But when I run this code it runs correctly and returns false.

Is the way I'm checking a safe and correct way to check?

like image 313
Zapnologica Avatar asked Mar 31 '14 07:03

Zapnologica


1 Answers

Yes, this is the safe and correct way. Your colleague probably has some weird understanding of operator precedence or boolean expression evaluation in C# :)

The || operator (the same as &&) will stop evaluating as soon as it can be sure of the results. Since boolean OR can never yield false as soon as one of the operands is true, it will either fail on the first operand (if it's null, the result is true => you're done), or it will evaluate both of the operators.

Of course, if you're not averse to using extension methods, this can be handily used to simplify the condition. Eg. you can use an extension method like this:

public static bool IsEmpty<T>(List<T> @this)
{
  return @this == null || @this.Count == 0;
}

Which then lets you use a condition like this:

if (users.IsEmpty())
{
  ...
}

Also, note that List<T> has a Count property - you should probably use that instead of the extension method Count(). In the end, it will do the same thing IIRC (it checks if the enumerable is a collection or a list, IIRC), but it goes through some loops to do that.

You might want to ask your colleague what he thinks will happen. You've got a simple test case that shows you're right, but perhaps he's got some reasons of his own why he doesn't want that. The most likely thing, however, is that he's used to a different programming language, and not actually a native C#-er. In that case, you've both gotten an opportunity to learn :)

like image 77
Luaan Avatar answered Sep 28 '22 23:09

Luaan