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 descriptionCalling 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.
To fix violations:
string.Concat
, andSubstring
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4