Is checking count/size/length less than 0 necessary in modern languages anymore? For instance, in C# I quote often will check if a collection’s count is less than or equal to 0.
I assume that this was done in older languages, like C, where you could potentially have a size of less than 0.
Is there ever a case where you can have the size/length/count of an object or primitive type be less than 0?
6
In the .NET Framework (of which the C# language is a part), most ordinary indexes (with the notable exception of file positions, which use a 64 bit signed long
) are standardized to a signed, 32 bit int
.
So, for example, when you get the length of a string, you’re being returned a number that can hold negative values, but in practice, will never be negative.
However, that’s not true of all string operations. IndexOf()
still returns a signed int
, but will return a value of -1 if the search string is not found. This is partly why signed int
was chosen for such indexes; to provide the possibility of returning negative values for signaling purposes.
Because signed integers are always returned from such operations, the code
if (s.length <= 0)
is consistent with the idea that “I’m checking to see if this string has something in it,” since all such lengths will be a positive number.
But you’re right; technically it’s not necessary to check for a negative number in those cases where you’ll never get one (i.e. Length).
3
You can use Any
which will return as soon as if there is an item in the collection, whereas using Length
will actually iterate through the whole collection and count it, which is a bad idea. So Any
is lazy, Length
is eager. Most of the cases, Any
is sufficient.
1