Suggest using string's indexer property over toCharArray()

Este producto no es compatible con el sitio Datadog seleccionado. ().
Esta página aún no está disponible en español. Estamos trabajando en su traducción.
Si tienes alguna pregunta o comentario sobre nuestro actual proyecto de traducción, no dudes en ponerte en contacto con nosotros.

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

Integraciones sin problemas. Prueba la Seguridad de Código de Datadog