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

Code analysis

CA1845: Use span-based 'string.Concat'

Learn about code analysis rule CA1845: Use span-based 'string.Concat'

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

Cause

This rule locates string-concatenation expressions that contain System.String.Substring calls and suggests replacing System.String.Substring with System.MemoryExtensions.AsSpan and using the span-based overload of System.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.

csharp
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