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

  • 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

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

    Like

  • 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

  • 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

  • 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 Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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