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 :)