ASP.NET C# how to make String.Contains case-insensitive

How to compare two strings in c# which is case-insensitive using String.Contains() method. With the use of IndexOf() method we can simply make compare two strings easily.

compareString.IndexOf("search string", 0, StringComparison.CurrentCultureIgnoreCase) >= 0


Returns zero-based index position of value if that string is found.

returns 0 if value is String.Empty,
returns -1 if string is not matched,
either returns zero-based index position of the value.


Simple case is we always make use of String.Contains() while comparing two strings and convert to upper before comparing like this.




Now let us make a extension helper method for String.Contains() in C#.

 public static class StringExtensions
 public static bool Contains(this string source, string toCheck, bool bCaseInsensitive )
 return source.IndexOf(toCheck, bCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;


And now we can call this while making comparison on any string easily.


compareString.Contains(searchStr, true);


Happy Coding!


Back to top