Редагувати

Поділитися через


CA1845: Use span-based 'string.Concat'

Property Value
Rule ID CA1845
Title Use span-based 'string.Concat'
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

This rule locates string-concatenation expressions that contain Substring calls and suggests replacing Substring with AsSpan and using the span-based overload of String.Concat.

Rule description

Calling Substring produces a copy of the extracted substring. By using AsSpan instead of Substring and calling the overload of string.Concat that accepts spans, you can eliminate the unnecessary string allocation.

How to fix violations

To fix violations:

  1. Replace the string concatenation with a call to string.Concat, and
  2. Replace calls to Substring with calls to AsSpan.

The following code snippet shows examples of violations, and how to fix them.

using System;

class Example
{
    public void Method()
    {
        string text = "fwobz the fwutzle";

        //  Violation: allocations by Substring are wasteful.
        string s1 = text.Substring(10) + "---" + text.Substring(0, 5);

        //  Fixed: using AsSpan avoids allocations of temporary strings.
        string s2 = string.Concat(text.AsSpan(10), "---", text.AsSpan(0, 5));
    }
}

When to suppress warnings

Do not suppress warnings from this rule. There is no reason to use Substring over AsSpan when the extracted substring is only being passed to a method with a span-based equivalent.

See also