Does one string contain another, irrespective of case?

One of the methods that's noticeable by its absence from the .NET Framework / .NET Core (or, to put it another way .NET Standard 2.0) is an override of string.Contains that takes a StringComparison value. Put another way, "Hello world!".Contains("hello") will return false (and rightly so!) because the casing of the string being looked for differs from the casing of the string being looked in.

It feels like most projects I work on end up with an extension method that allows me to specify that I want to ignore the case of the strings, "real world" use of strings isn't generally case sensitive! Here's the stripped back version of the extension method, if you use it, remember to add checks on the parameters passed in!

public static class StringExtensions
    public static bool Contains(this string source, string toCheck, StringComparison comp)
        return source.IndexOf(toCheck, comp) >= 0;

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment