Like (contains) in c# with a string extension

This is an extension to make a contains between 2 sting :

public static class StringExtensions
   public static bool Contains(this String str, String substring, 
                               StringComparison comp)
      if (substring == null)
         throw new ArgumentNullException("substring", 
                                         "substring cannot be null.");
      else if (! Enum.IsDefined(typeof(StringComparison), comp))
         throw new ArgumentException("comp is not a member of StringComparison",

      return str.IndexOf(substring, comp) >= 0;                      


To use it just do this :

 string s = "This is a string.";
 string sub1 = "this";
 s.Contains(sub1, comp) // return true

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s