77

How can I make the following case insensitive?

myString1.Contains("AbC")
3
  • 1
    Or duplicate of MSDN article for String.Contains which suggests to "See also: IndexOf"... Commented Jul 10, 2013 at 6:50
  • Well, this question is not a 100%-duplicate if it asks for answers in VB.Net, since VB.Net has features C# does not have, like the LIKE operator which could be used here. Commented Jul 10, 2013 at 7:49
  • He tagged both languages, so probably he doesn't care about which one the solution is, so the duplicate completly answer this question. Anyway, if he edits his question with onlt vb.net then it will enter the reopen queue automatically. Commented Jul 10, 2013 at 8:01

3 Answers 3

146

You can create your own extension method to do this:

public static bool Contains(this string source, string toCheck, StringComparison comp)
  {
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
  }

And then call:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);
Sign up to request clarification or add additional context in comments.

5 Comments

This is arguably the best answer by wrapping it in an extension method.
@Moo-Juice Yes because it is familiar :) stackoverflow.com/a/444818/447156
I would recommend calling the function something other than an exact match with something in the framework like your initials + Contains. I use this approach for a ton of things. My initials are PS so I have psContains, psStartsWith, psEndsWith, etc. The reason I think it should be different is so you can tell, just by reading the code, what it's going to do. Also, the if the signatures are compatible, the compiler might not like it. If they are compatible enough, compiling wouldn't help find you find out if your extensions are in play. Extensions are a real gem of Dotnet. If used correctly :)
I wish I could give you more than one up-vote!
You should check to see if the string and the toCheck argument are null. If either is null then you should return false. Otherwise it is going to throw a exception.
51

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

1 Comment

Two typos in your answer, otherwise good ;-) It should be (obviously) StringComparison.OrdinalIgnoreCase
13
bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);

[EDIT] extension code:

public static bool Contains(this string source, string cont
                                                    , StringComparison compare)
{
    return source.IndexOf(cont, compare) >= 0;
}

This could work :)

4 Comments

This method is not present in standard C#
This is the reason for the question... Thanks @trippino
@trippino edited my answer with extension code
This is good and simple answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.