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