Case insensitive Contains method for a string class


I decided that in the next few weeks I will write series of short blog posts with code snippets that I use during my everyday work.

Very often I have to check if a string contains specific sequence of characters, to do it I write something like this:

if (text.Contains("some text"))
{
  DoSomething();
}

and after few seconds I realize that it won’t work correctly because Contains method is case-sensitive. To solve this problem I’ve written an extension method that does case-insensitive checking. Here is my method:

public static class StringExtensionMethods
{
  public static bool ContainsWithIgnoreCase(this string text, string value)
  {
     if (text == null)
     {
         return false;
     }
     return 
     	(text.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0);
  }
}

and now I can simply write:

if (text.ContainsWithIgnoreCase("some text"))
{
  DoSomething();
}

At the beginning of the extension method I check if text isn’t null and if so I return false. This causes that I don’t have to check if a variable is null before using this method.


You may also like

Lesser known Clojure: variants of threading macro

ClojureScript: JavaScript Interop

Template method pattern