Skip to content

CA1831 and CA1846 don't fire when combining range syntax with Substring #6907

Open

Description

Analyzer

Diagnostic ID:
CA1831: Use AsSpan instead of Range-based indexers for string when appropriate
CA1846: Prefer AsSpan over Substring

Analyzer source

SDK: Built-in CA analyzers in .NET 5 SDK or later

Version: SDK 8.0.100-preview.7.23376.3

Describe the bug

The following code generates CA1831: Use AsSpan instead of Range-based indexers for string when appropriate:

void Foo(string str, int position)
{
    var foo = string.Concat(str[0..position], str.AsSpan(position + 1));
}

And the following code generates CA1846: Prefer AsSpan over Substring:

void Foo(string str, int position)
{
    var foo = string.Concat(str.Substring(0, position), str.Substring(position + 1));
}

All is good. In both cases, an analyzer warning is issued suggesting more efficient code. However, if I combine these two - use the range syntax in one argument and Substring in the other, like this:

void Foo(string str, int position)
{
    var foo = string.Concat(str[0..position], str.Substring(position + 1));
}

Suddenly, no diagnostic is issued. Both analyzers are silent. I think this code should produce a warning as well, be it either CA1831 or CA1846, or both.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions