C# String.Contains Case Insensitive Extension Method

public static bool ContainsCaseInsensitive(this string source, string value)

{

int results = source.IndexOf(value, StringComparison.CurrentCultureIgnoreCase);

return results == –1 ? false : true;

}

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

9 thoughts on “C# String.Contains Case Insensitive Extension Method

  1. Even shorter and more flexible:
    public static bool Contains(this String item, String subString, StringComparison comparison)
    {
    return item.IndexOf(item, comparison) != -1;
    }

    //Ooops, previous was wrong;)

    Like

  2. Even shorter and more flexible:
    public static bool Contains(this String item, String subString, StringComparison comparison)
    {
    return item.IndexOf(item, comparison) == -1;
    }

    Like

  3. Hey Sectoid, whats up with the extra parameter “String subString” its not being used within the method logic? Let us know we are curious.

    Like

  4. Way to get all the examples in the comments wrong guys.

    It shoud be != -1, and subString should be used instead of item as the first parameter of IndexOf

    Like

  5. Best of both worlds (flexibility and terse syntax)

    public static bool Contains(this string source, string value, StringComparison comparisonType)
    {
    return source.IndexOf(value, comparisonType) != -1;
    }

    public static bool Contains(this string source, string value, bool ignoreCase)
    {
    return ignoreCase ? source.Contains(value, StringComparison.InvariantCultureIgnoreCase) : source.Contains(value, StringComparison.InvariantCulture);
    }

    Like

Leave a comment