
## Review A dedicated reviewer checked the rule description successfully for: - [ ] logical errors and incorrect information - [ ] information gaps and missing content - [ ] text style and tone - [ ] PR summary and labels follow [the guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
56 lines
1.7 KiB
Plaintext
56 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The `string` type offers an indexer property that allows you to treat it as a `char` array. Therefore, if you just need to access a specific character or iterate over all of them, the `ToCharArray` call should be omitted. For these cases, not omitting makes the code harder to read and less efficient as `ToCharArray` copies the characters from the `string` object into a new Unicode character array.
|
|
|
|
The same principle applies to https://devblogs.microsoft.com/dotnet/csharp-11-preview-updates/#utf-8-string-literals[utf-8 literals types] (`ReadOnlySpan<byte>`, `Span<byte>`) and the https://learn.microsoft.com/en-us/dotnet/api/system.span-1.toarray?view=net-7.0[`ToArray`] method.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
string str = "some string";
|
|
foreach (var c in str.ToCharArray()) // Noncompliant
|
|
{
|
|
// ...
|
|
}
|
|
|
|
ReadOnlySpan<byte> span = "some UTF-8 string literal"u8;
|
|
foreach (var c in span.ToArray()) // Noncompliant
|
|
{
|
|
// ...
|
|
}
|
|
----
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
string str = "some string";
|
|
foreach (var c in str)
|
|
{
|
|
// ...
|
|
}
|
|
|
|
ReadOnlySpan<byte> span = "some UTF-8 string literal"u8;
|
|
foreach (var b in span) // Compliant
|
|
{
|
|
// ...
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.string.tochararray[String.ToCharArray Method]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#accessing-individual-characters[Accessing individual characters]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-11.0/utf8-string-literals[UTF-8 Strings literals]
|
|
|
|
|
|
include::./rspecator.adoc[]
|