Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
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 stringsif(foo.ToUpper()==bar.ToUpper()){}
// do not use `==` to compare stringsif(foo.ToLower()==bar.ToLower()){}