CA1860: Avoid using 'Enumerable.Any()' extension method
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1860
Does this rule make any sense?
The rule description says: "To determine whether a collection type has any elements, it's more efficient and clearer to use the Length, Count, or IsEmpty (if possible) properties than to call the Enumerable.Any method. Any(), which is an extension method, uses language integrated query (LINQ). It's more efficient to rely on the collection's own properties, and it also clarifies intent."
Does using Count truly clarify intent? I was always using .Any() because I thought it is far clearer -
I really miss an
But VisualStudio yells at me now and suggests me to use
Also note that
The rule description mentions the
Finally the rule mentions performance, but isn't this a typical case of premature optimization? Unless I'm in a tight loop, the 10ms saved by avoid
Am I missing something? Are there really any outstanding reasons to avoid
Does this rule make any sense?
The rule description says: "To determine whether a collection type has any elements, it's more efficient and clearer to use the Length, Count, or IsEmpty (if possible) properties than to call the Enumerable.Any method. Any(), which is an extension method, uses language integrated query (LINQ). It's more efficient to rely on the collection's own properties, and it also clarifies intent."
Does using Count truly clarify intent? I was always using .Any() because I thought it is far clearer -
Count != 0 just asks to be extracted into a method, the intent is not to check the number of elements, but whether the collection has Any elements.I really miss an
Empty property or method, but the next best thing is !collection.Any() or, even better, an extension method: public static Empty<T>(this IEnumerable<T> enumerable) => !enumerable.Any().But VisualStudio yells at me now and suggests me to use
Count == 0 or Count != 0 instead.Also note that
Count bears the risk of accidentally messing up != with == or vice-versa.The rule description mentions the
IsEmpty property, but note that the two most common cases (List and Array) have no such property.Finally the rule mentions performance, but isn't this a typical case of premature optimization? Unless I'm in a tight loop, the 10ms saved by avoid
.Any() won't matter, and .Any() does seem clearer, which is what matters.Am I missing something? Are there really any outstanding reasons to avoid
Any()? Because I feel ready to rebel and just suppress this suggestion.Learn about code analyzer rule CA1860 - Avoid using 'Enumerable.Any()' extension method
