C#idiomatic C#
ca1826fundamentals/code-analysis/quality-rules

Code analysis

CA1826: Use property instead of Linq Enumerable method

Learn about code analysis rule CA1826: Use property instead of Linq Enumerable method

CA1826 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

The System.Linq.Enumerable LINQ method was used on a type that supports an equivalent, more efficient property.

Rule description

This rule flags the System.Linq.Enumerable LINQ method calls on collections of types that have equivalent but more efficient properties to fetch the same data.

This rule analyzes collection types that implement System.Collections.Generic.IReadOnlyList but not System.Collections.Generic.IList.

This rule flags calls to the following methods on these collection types:

The analyzed collection types and methods may be extended in the future to cover more cases.

How to fix violations

To fix a violation, replace the System.Linq.Enumerable method call with property access. For example, the following two code snippets show a violation of the rule and how to fix it:

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class C
{
    public void M(IReadOnlyList<string> list)
    {
        Console.Write(list.First());
        Console.Write(list.Last());
        Console.Write(list.Count());
    }
}
csharp
using System;
using System.Collections.Generic;

class C
{
    public void M(IReadOnlyList<string> list)
    {
        Console.Write(list[0]);
        Console.Write(list[list.Count - 1]);
        Console.Write(list.Count);
    }
}

When to suppress warnings

It's safe to suppress a violation of this rule if you're not concerned about the performance impact from specific System.Linq.Enumerable method calls.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1826
// The code that's violating the rule is on this line.
#pragma warning restore CA1826

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1826.severity = none

For more information, see How to suppress code analysis warnings.

Configure code to analyze

Use the following option to configure which parts of your codebase to run this rule on.

Exclude FirstOrDefault and LastOrDefault methods

You can configure this rule to exclude the System.Linq.Enumerable.FirstOrDefault and System.Linq.Enumerable.LastOrDefault methods from analysis. You might consider excluding these methods if readability is a concern, since the code you'd write to replace them is not easily readable. To exclude these methods, add the following key-value pair to an .editorconfig file in your project:

ini
dotnet_code_quality.CA1826.exclude_ordefault_methods = true

See also