Use span-based 'string.Concat'
Use span-based 'string.Concat'
Microsoft docsDescription
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.
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.
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.
Example
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
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.