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