The Count
or Length
property or the Count<TSource>(IEnumerable<TSource>) extension method was used to determine whether or not the object contains any items by comparing the value to 0
or 1
, and the object has a more efficient IsEmpty
property that could be used instead.
This rule flags the calls to the Count
and Length
properties or Count<TSource>(IEnumerable<TSource>) and LongCount<TSource>(IEnumerable<TSource>) LINQ methods when they are used to determine if the object contains any items and the object has a more efficient IsEmpty
property.
The analysis of this rule originally overlapped with similar rules CA1827, CA1828, and CA1829; the analyzers of such rules were merged along with the one for CA1836 to report the best diagnosis in case of overlap.
How to fix violationsTo fix a violation, replace the Count<TSource>(IEnumerable<TSource>) or LongCount<TSource>(IEnumerable<TSource>) method call or the Length
or Count
property access when it's used in an operation that determines if the object is empty with use of the IsEmpty
property access. For example, the following two code snippets show a violation of the rule and how to fix it:
using System.Collections.Concurrent;
class C
{
ConcurrentQueue<int> _queue;
public bool IsEmpty => _queue.Count == 0;
}
using System.Collections.Concurrent;
class C
{
ConcurrentQueue<int> _queue;
public bool IsEmpty => _queue.IsEmpty;
}
Tip
A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press Ctrl+. (period). Choose Prefer 'IsEmpty' over 'Count' to determine whether the object contains or not any items from the list of options that's presented.
When to suppress warningsIt's safe to suppress a violation of this rule if you're not concerned about the performance impact from unnecessary item enumeration to compute the count.
Suppress a warningIf you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1836
// The code that's violating the rule is on this line.
#pragma warning restore CA1836
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1836.severity = none
For more information, see How to suppress code analysis warnings.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4