Pro EP 16 : Do and Don’ts for String Usage

Muhammad Waseem
Become .NET Pro !
1 min readMar 1, 2023

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

  1. Subscribe my Weekly .NET Newsletter of C#/.NET
  2. Follow me on LinkedIn/Twitter OR Clap at least 50 times.
  3. Get exclusive .NET Questions & Answers by becoming a Patron , I add almost 25+ new questions with explanation per month.
  4. Download my eBook at Gum road that contains 30+ .NET Tips.

--

--