For a long time now I've been in the habit of checking whether a collection (array, dictionary, whatever) is non-empty with a nonequality. Like this:
if ( MyArray.Length < 1 )
{
// Do something if the array is empty
}
Sometimes I do this for strings too, and other kinds of collections. In practice, this should be the same as
if ( MyArray.Length == 0 )
{
// Do something if the array is empty
}
Because the length of collection should never be less than 0 anyway, right? So I always thought - what the heck, I'll include the inequality and be double-safe even in the case the sky falls down.
But today a though struck me that the second version might be more readable than the first. It expresses more clearly that the case I'm looking for is the empty array, which is not immediately apparent from the first version. So maybe I should use that instead? Since, you know, if a collection length is less than 0, then I'm screwed anyway.
Which version do you use, and which would you suggest others to use (and why)?
Clarification: This was meant as a question about simple collections, where obtaining .Length
is O(1) or otherwise inexpensive. If .Length
itself is a nontrivial operation (such as necessitating the iteration through a linked list, or contacting the DB), then this is the wrong approach altogether.
The question was about x < 1
vs x == 0
where x is a nonnegative integer (although it might not be typed as such).