views:

568

answers:

4

Are .NET string functions like IndexOf("blah") case sensitive?

From what I remember they aren't, but for some reason I am seeing bugs in my app where the text in the query string is in camel case (like UserID) and I'm testing for IndexOf("userid").

+11  A: 

Yes, string functions are case sensitive by default. They typically have an overload that lets you indicate the kind of string comparison you want. This is also true for IndexOf. To get the index of your string, in a case-insensitive way, you can do:

string blaBlah = "blaBlah";
int idx = blaBlah.IndexOf("blah", StringComparison.OrdinalIgnoreCase);
driis
C# is stricly case sensitive, but in VB.NET, you could use OPTION COMPARE TEXT to force a non case sensitive comparison. The default in VB.NET is BINARY so it behave like C#.
Pierre-Alain Vigeant
Even so, `Option Compare` only applies to VB comparison operators such as `=` and `Like` - it will not affect any methods of `String`, nor any other FCL string functions.
Pavel Minaev
+1  A: 

.NET string comparisons are indeed case sensitive. You could use things like ToUpper() to normalize things before comparing them.

Jim Blake
Another option would be: CultureInfo.CurrentCulture.CompareInfo.IndexOf(source, value, CompareOptions.IgnoreCase)
Marcel J.
Be careful about cultures, or you might suddenly find the comparison not working on a Turkish system - in Turkish, i uppercases to İ.
Michael Madsen
using either ToUpper or ToLower is a bad idea since it would require initialization of a new object (bad for performance) all string comparison methods either takes a StringComparison argument or a IComparer argument in one of the overloads using one of those will out perform ToUpper/ToLower
Rune FS
A: 

As default they are case sensitive but most of them (if not all) including IndexOf has an overload that takes a StringComparison argument. E.g. if you pass

StringComparison.InvariantCultureIgnoreCase

as the StringComparison argument to IndexOf it will (as the name implies) ignore case differences

Rune FS
+2  A: 

One thing I'd like to add to the existing answers (since you were asking about ASP.NET):

Some name/value collections, such as the Request.QueryString and probably also Request.Form are not case-sensitive. For example if I navigate to an ASPX page using the following URL

http://server/mypage.aspx?user=admin

then both of the following lines will return "admin":

var user1 = Request.QueryString["user"];
var user2 = Request.QueryString["USER"];
M4N