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

Code analysis

CA1870: Use a cached 'SearchValues' instance

Learn about code analyzer rule CA1870 - Use a cached 'SearchValues' instance

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

Cause

An IndexOfAny or ContainsAny method is called with many constant values in a way that can benefit from using System.Buffers.SearchValues instead.

The rule doesn't flag calls that use up to five values, as those already use an optimal implementation.

Rule description

Using a cached System.Buffers.SearchValues instance is more efficient than passing values to IndexOfAny or ContainsAny directly.

How to fix violations

Create and cache a System.Buffers.SearchValues instance in a static readonly field, then pass that instance to the IndexOfAny or ContainsAny call instead.

A code fix that automatically performs this transformation is available.

Example

The following code snippet shows two violations of CA1870:

csharp
static readonly char[] MyValues = new[] { 'a', 'b', 'c', 'x', 'y', 'z' };

static int IndexOfMyValues(ReadOnlySpan<char> text)
{
    return text.IndexOfAny(MyValues);
}

static bool ContainsOnlyMyValues(ReadOnlySpan<char> text)
{
    return !text.ContainsAnyExcept("abcxyz");
}

The following code snippet fixes the violations:

csharp
private static readonly SearchValues<char> s_myValues = SearchValues.Create("abcxyz");

static int IndexOfMyValues(ReadOnlySpan<char> text)
{
    return text.IndexOfAny(s_myValues);
}

static bool ContainsOnlyMyValues(ReadOnlySpan<char> text)
{
    return !text.ContainsAnyExcept(s_myValues);
}

If there are multiple calls to IndexOfAny with the same set of values, s_myValues should be reused.

When to suppress warnings

It's safe to suppress this warning if performance isn't a concern.

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 CA1870
// The code that's violating the rule is on this line.
#pragma warning restore CA1870

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

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

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

See also