This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
| Property | Value |
|---|---|
| Rule ID | CA1870 |
| Title | Use a cached 'SearchValues' instance |
| Category | Performance |
| Fix is breaking or non-breaking | Non-breaking |
| Enabled by default in .NET 10 | As suggestion |
AnIndexOfAny orContainsAny method is called with many constant values in a way that can benefit from usingSearchValues instead.
The rule doesn't flag calls that use up to five values, as those already use an optimal implementation.
Using a cachedSearchValues<T> instance is more efficient than passing values toIndexOfAny orContainsAny directly.
Create and cache aSearchValues<T> instance in astatic readonly field, then pass that instance to theIndexOfAny orContainsAny call instead.
Acode fix that automatically performs this transformation is available.
The following code snippet shows two violations of CA1870:
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:
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 toIndexOfAny with the same set of values,s_myValues should be reused.
It's safe to suppress this warning if performance isn't a concern.
If 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 CA1870// The code that's violating the rule is on this line.#pragma warning restore CA1870To disable the rule for a file, folder, or project, set its severity tonone in theconfiguration file.
[*.{cs,vb}]dotnet_diagnostic.CA1870.severity = noneFor more information, seeHow to suppress code analysis warnings.
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?