I saw in many code snippets that the following condition is used to check whether a list is empty:
List<string> someList = someFunctionThatPopulatesAList();
if (someList == null || someList.Count <= 0)
return;
I'm wondering - why not use the following condition instead:
if (someList == null || someList.Count == 0)
return;
Is there any case in which List<T>.Count
is negative?
You can simply try to use Any() like
if ((someList!= null) && (!someList.Any())) {
}
Do note that you can use it if the list uses the IEnumerable<T>
and you want to use the LINQ option.
Is there any case in which List.Count is negative?
No its not. Actually whenever you are using operations like Count
or length
then a signed integer is returned, so it more of like an implementation to check that you are implementing it to check if it is a positive result.(However techincially you don't need to make that check. Its more of like an idea implementation.)