Reputation: 761
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?
Upvotes: 3
Views: 5276
Reputation: 2580
Null-Conditional Operator Even the newest .NET developers are likely familiar with the NullReferenceException. This is an exception that almost always indicates a bug because the developer didn’t perform sufficient null checking before invoking a member on a (null) object.
if(someList?.Any()){
//Something
}
Upvotes: 0
Reputation: 28499
As others have said: Using Any()
is a good solution.
There are two separate aspects why using Length <= 0
when using Length
is better when compared to Length == 0
.
It is safer with respect to reusing the code. The code could change to use some other list class other than the standard .net List<> implementation and that other list class could under some circumstances return a negative value for Length(). Creating such a class would be a very bad idea in my opinion, but sometimes people choose to follow bad ideas, so better safe than sorry.
When using code analysis tools, this would allow the code analysis tool to know that Length
has a positive value and could improve the ability of the tool to make a meaningful analysis of your code.
Upvotes: 1
Reputation: 9749
Yes you are correct, it is not necessary to use that.
You can also use Any()
extenstion method as suggested by @Rahul.
But because you are checking on a List<T>
is it suggested to use Count()
, it would be slightly faster, as the size is already known.
- Use Count if you're using a list, since it knows it's size.
- Use Length for an Array
- If you just have an IEnumerable I would use .Any() over .Count() as it will be faster since it stops after checking one item.
Ref - List<T> Any or Count?
Upvotes: 1
Reputation: 172448
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.)
Upvotes: 5