rspec/rules/S3456/csharp/rule.adoc

56 lines
1.7 KiB
Plaintext
Raw Normal View History

== 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.
2021-04-28 16:49:39 +02:00
2023-06-28 14:02:20 +02:00
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.
2023-06-28 14:02:20 +02:00
== How to fix it
2021-04-28 16:49:39 +02:00
2023-06-28 14:02:20 +02:00
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
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
{
// ...
}
2021-04-28 16:49:39 +02:00
----
2023-06-28 14:02:20 +02:00
==== Compliant solution
2021-04-28 16:49:39 +02:00
2023-06-28 14:02:20 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
string str = "some string";
foreach (var c in str)
{
// ...
}
ReadOnlySpan<byte> span = "some UTF-8 string literal"u8;
foreach (var b in span) // Compliant
{
// ...
}
2021-04-28 16:49:39 +02:00
----
2023-06-28 14:02:20 +02:00
== Resources
2023-06-28 14:02:20 +02:00
=== Documentation
2023-06-28 14:02:20 +02:00
* 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[]