이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

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

Seamless integrations. Try Datadog Code Security

PREVIEWING: pmartinez/rum-server-uninstall