by Sai gowtham

How to check if String contains case insensitive in C#

We can check if a string contains a substring which is case insensitive by using the String.IndexOf() Method and pass StringComparison.OrdinalIgnoreCase as the type of search to use.

Example:

string title = "How are YOU";
bool contains = title.IndexOf("you", StringComparison.OrdinalIgnoreCase) >= 0;

Defining CaseInsenstive method

We can also define our CaseInsenstive method like this.

public static class Extensions
{
    public static bool CaseInsensitive(this string text, string value,
        StringComparison stringComparison = StringComparison.CurrentCultureIgnoreCase)
    {
        return text.IndexOf(value, stringComparison) >= 0;
    }
}

Usage:

string title = "How are YOU";
bool contains = title.CaseInsensitive('you');

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course