The example creates more questions than it answers
- Dominant language
- No language data
- Stars
- 4.8k
- Forks
- 6.1k
- Avg merge
- 15h 21m
- Merged PRs (30d)
- 370
Description
### Type of issue
Other (describe below)
### Description
[Enter feedback here]
When contrasting two different things, its confusing when you change other things at the same time in the example.
``` csharp
// 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));
```
The CA rule is to avoid using `Substring` and to use `AsSpan` when concatenating strings. Now I have to figure out why you also changed the `+` to `Concat` and if that has any bearing on this specific CA warning (I dont imagine it does, but then any place I'm doing string concatenation like this its either in StringBuilder or interpolation).
Instead of changing the entire way to constructed the string as well as showing how to use `AsSpan`, the examples should have read
``` csharp
string s2 = text.AsSpan(10) + "---" + text.AsSpan(0, 5);
//or
string s1 = string.Concat(text.Substring(10), "---", text.Substring(0, 5));
````
... or both use interpolation for both examples like everyone should be doing anyway. This was literally the first CA new rule I looked at. I hope this was just a fluke and not a new pattern.
### Page URL
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1845
### Content source URL
https://github.com/dotnet/docs/blob/main/docs/fundamentals/code-analysis/quality-rules/ca1845.md
### Document Version Independent Id
fe382ed1-8dc1-f5d8-df87-83a2ca0a70ca
### Article author
@NewellClark
### Metadata
* ID: 86d4c333-75b8-e18a-331f-6036d292ebfc
* Product: **dotnet-fundamentals**
Contributor guide
Assessment
This issue has not been assessed yet.