Site icon Ryadel

ASP.NET C# - Case-insensitive String.Contains Helper & Extension Method

ASP.NET C# - Case-insensitive String.Contains Helper & Extension Method

If you stumbled upon this post it probably means that you're trying to use the String.Contains  method in a C# application in a case-insensitive way: as a matter of fact, there isn't a built-in overload method accepting a StringComparison  options object, hence is not possible to do that.

To work around it, most programmers just do something like this:

However, I prefer to use the following extension method, which does the same thing in a much cleaner way and also with better performances:

The method can be used either as standard method by implementing it in a static class or also as an extension method, in the following way:

Potential issue with different Cultures

This solution will work fine for english and latin-based cultures, where the upper-case and lower-case rules works the way we're used to. That's not true for some specific Cultures: think about the Turkish language, where the upper-case version of the 'i' letter is the unfamiliar character 'İ'... Meaning that the strings "ICON" and "icon", which are the same word in English, are treated in Turkish as they are two different word.

If you're dealing with these kind of cultures, the above method won't work properly, unless that culture is the exact same one the application is running with - that being the case, you could just use StringComparison.CurrentCultureIgnoreCase  and be done with. If that's not the case, you should fetch the CultureInfo  object describing the language that the text you need to compare and use the IndexOf  method provided by that class instead, in the following way:

Meaning that our extension method should be something like this:

Once done, we can use it in the following way:

The exact same logic also applies to all other string-comparison based methods, such as Compare , Replace ,  StartsWith / EndsWith , and so on.

That's about it: happy coding!

 

 

Exit mobile version