CRR0050 - String.Compare can be used
- 2 minutes to read
This analyzer identifies string comparison expressions which can be replaced with a string.Compare call to improve code readability and provide comparison options such as culture-specific or case-insensitive comparisons.
bool CheckError(string msg) {
if (msg.Substring(1, 4) == "Error")
return true;
return false;
}
How to Fix Violations
To fix this issue, use the string.Compare method call instead of the == (= in Visual Basic) or != operator (<> in Visual Basic):
bool CheckError(string msg) {
if (string.Compare(msg.Substring(1, 4), "Error", false) == 0)
return true;
return false;
}
Call the Use string.Compare refactoring to convert the comparison with the equality operator or inequality operator to a comparison with the string.Compare method.
When to Suppress Warnings
You may want to suppress CRR0050 if your comparison is strictly for equality.
Use string.Compare when:
- You need to determine ordering between strings (for example, sorting or lexicographic comparison)
- You require culture-aware comparisons (for example, the Turkish i problem)
- You want case-insensitive comparisons (for example, a file path in Windows)
Use == when:
- You want a simple, case-sensitive, ordinal equality check
- You compare strings in performance-critical code and do not need culture or case flexibility
See Also