Suggest using string's indexer property over toCharArray()

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

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}");
		}
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: mcretzman/DOCS-9337-add-cloud-info-byoti