Suggest using string's indexer property over toCharArray()
このページは日本語には対応しておりません。随時翻訳に取り組んでいます。
翻訳に関してご質問やご意見ございましたら、
お気軽にご連絡ください。
ID: csharp-best-practices/redundant-tochararray
Language: C#
Severity: Warning
Category: Best Practices
Description
When using a for each
statement to iterate over a string’s characters, using ToCharArray()
is redundant and unnecessary, as the string
type has indexer that allows access to each char
.
Non-Compliant Code Examples
class NonCompliant
{
public static void Main()
{
string str1 = "foo";
foreach (char ch in str1.toCharArray())
{
Console.WriteLine($"{ch}");
}
foreach (char ch in "foo".toCharArray())
{
Console.WriteLine($"{ch}");
}
var obj1 = new { str1 = "foo" };
foreach (char ch in obj1.str1.toCharArray())
{
Console.WriteLine($"{ch}");
}
}
}
Compliant Code Examples
class Compliant
{
public static void Main()
{
string str1 = "foo";
foreach (char ch in str1)
{
Console.WriteLine($"{ch}");
}
foreach (char ch in "foo")
{
Console.WriteLine($"{ch}");
}
var obj1 = new { str1 = "foo" };
foreach (char ch in obj1.str1)
{
Console.WriteLine($"{ch}");
}
}
}