Pro EP 12 : Compare Strings in C# and Ignore Case

Muhammad Waseem
Become .NET Pro !
1 min readFeb 24, 2023

❌ We can compare two strings using == and to ignore case we can convert both strings to lower , it will work fine , but it’s not good approach.

✔ We have two methods available for string comparison, those are overloads of 𝚜𝚝𝚛𝚒𝚗𝚐.𝙲𝚘𝚖𝚙𝚊𝚛𝚎 method which takes three parameters two strings and comparison case. As per the docs Microsoft suggests to use 𝚂𝚝𝚛𝚒𝚗𝚐𝙲𝚘𝚖𝚙𝚊𝚛𝚒𝚜𝚘𝚗.𝙾𝚛𝚍𝚒𝚗𝚊𝚕 and 𝚂𝚝𝚛𝚒𝚗𝚐𝙲𝚘𝚖𝚙𝚊𝚛𝚒𝚜𝚘𝚗.𝙾𝚛𝚍𝚒𝚗𝚊𝚕𝙸𝚐𝚗𝚘𝚛𝚎𝙲𝚊𝚜𝚎 for string comparison.

🎯 𝚂𝚝𝚛𝚒𝚗𝚐𝙲𝚘𝚖𝚙𝚊𝚛𝚒𝚜𝚘𝚗.𝙾𝚛𝚍𝚒𝚗𝚊𝚕 : Use it when you need better performance comparison and you care about case sensitivity.
𝚂𝚝𝚛𝚒𝚗𝚐𝙲𝚘𝚖𝚙𝚊𝚛𝚒𝚜𝚘𝚗.𝙾𝚛𝚍𝚒𝚗𝚊𝚕𝙸𝚐𝚗𝚘𝚛𝚎𝙲𝚊𝚜𝚎 : Use it when case sensitivity is not needed.

🎯 We can use 𝚂𝚝𝚛𝚒𝚗𝚐. 𝙴𝚚𝚞𝚊𝚕 method as well passing it both strings and String Comparison case as well (e.g. Ordinal, OrdinalIgnoreCase)

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.

--

--