Count > 0 vs Count != 0

I came across an issue today that I think perfectly exhibits the principal of forward thinking in coding.  Consider the following block of code:

IList<MyObject> myList = myAdapter.Read();
if (myList.Count != 0)
… do some work …

The if statement is only executing its contents if the count of objects in the list is not zero.  This seems pretty harmless on the surface.  We’re taking an IList<T> after all and we know that List<T>.Count returns zero if the list is empty.  Therein lies the trap.  We’re not necessarily talking about List<T> here, we’re talking about any class that implements the IList<T> interface.  You can see the facepalm coming a mile away.

What if a class implements IList<T> and decides to return -1 for .Count to represent an empty collection.  This is actually more common than you’d think as there seem to be a large number of people out there who still use -1 as a return code for anything that is empty or not initialized.  The solution here would be to instead check for:
if (myList.Count > 0)

Instead of checking for Count != 0, we instead check if Count is greater than zero.  It doesn’t matter now whether the IList<T> implementation returns 0, -1, or -999 for Count to indicate an empty collection, the assertion that the if block should only run on a non-empty list still stands.

This entry was posted in Technology, Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *