Pro EP 16 : Do and Don’ts for String Usage
Following are the do and don’ts:
𝐃𝐨:
✅Use overloads that explicitly specify the string comparison rules for string operations. Typically, this involves calling a method overload that has a parameter of type StringComparison.
✅Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching and better performance
✅Use the non linguistic StringComparisonOrdinal or StringComparison OrdinalIgnoreCase values instead of string operations based on CultureInfo.InvariantCulture when the comparison is linguistically irrelevant (symbolic, for example)
✅Use the String.ToUpperInvariant method instead of the String.ToLowerInvariant method when you normalize strings for comparison.
✅Use an overload of the String.Equals method to test whether two strings are equal
✅Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.
𝐃𝐨𝐧’𝐭
❌Don’t use overloads that don’t explicitly or implicitly specify the string comparison rules for string operations.
❌Don’t use string operations based on StringComparison.InvariantCulture in most cases. One of the few exceptions is when you’re persisting linguistically meaningful but culturally agnostic data.
❌Don’t use an overload of the String.Compare or CompareTo method and test for a return value of zero to determine whether two strings are equal.
If you want to help the author in growing
- Subscribe my Weekly .NET Newsletter of C#/.NET
- Follow me on LinkedIn/Twitter OR Clap at least 50 times.
- Get exclusive .NET Questions & Answers by becoming a Patron , I add almost 25+ new questions with explanation per month.
- Download my eBook at Gum road that contains 30+ .NET Tips.