0 votes
by (2.5k points)

If I have two strings and want to check if they are the same, is something like this OK? 

string1.ToLower() == string2.ToLower()

So just tolowering both or I guess converting to uppercase as well?

1 Answer

0 votes
by (2.5k points)

Actually, the best way would be to use the string equals method. You can do this on an existing string like so : 

var string1 = "hello";
var string2 = "world";
string1.Equals(string2, StringComparison.InvariantCultureIgnoreCase);

But a better way might be to use the static String equals method because it can handle scenarios like this : 

string string1 = null;
var string2 = "world";
string.Equals(string1, string2, StringComparison.InvariantCultureIgnoreCase);

The reason you don't want to just ToLower is for a couple of reasons : 

  • In some languages, ToLower might not give you what you expect (e.g. Characters from other languages)
  • If one of the values is null, then calling ToLower() will throw an exception (Although this is easily avoidable, it's still a consideration)
  • But the biggest issue is that when you call ToLower() you are actually creating a new string in memory just to compare the values. On smaller strings you might not notice it but it can add up very quickly to performance bottlenecks on large strings. 
Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.