org.sonar.plugins.csharp.S3456.html Maven / Gradle / Ivy
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 utf-8 literals
types (ReadOnlySpan<byte>
, Span<byte>
) and the ToArray
method.
How to fix it
Code examples
Noncompliant code example
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
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