This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: csharp-best-practices/stringcomparison

Language: C#

Severity: Warning

Category: Best Practices

Description

The rule “Use StringComparison to compare strings” is critical in ensuring accurate and efficient string comparisons in C#. Using methods like ToUpper() or ToLower() or operators like == to compare strings can lead to incorrect results due to cultural differences in string representation. Furthermore, these methods can cause unnecessary memory allocation and performance issues.

The importance of this rule lies in its ability to prevent potential bugs and enhance the performance of your code. It ensures that string comparisons are done in a way that respects cultural differences and avoids unnecessary operations.

How to remediate

To adhere to this rule, always use the StringComparison enumeration when comparing strings. For example, use string.Equals(foo, bar, StringComparison.OrdinalIgnoreCase) instead of foo.ToUpper() == bar.ToUpper(). This will perform a case-insensitive, culture-invariant comparison that is also more performant.

Non-Compliant Code Examples

// do not use `==` to compare strings
if (foo.ToUpper() == bar.ToUpper())
{
}
// do not use `==` to compare strings
if (foo.ToLower() == bar.ToLower())
{
}

Compliant Code Examples

if (foo.Foo() == bar.Bar())
{
}
if (string.Equals(foo, bar, StringComparison.OrdinalIgnoreCase))
{
}
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 Datadog Code Security

PREVIEWING: guillaume.barrier/ERRORT-5095-general-doc-update