Tips for working with strings in C# 2.0
Working with strings is something all developers do all the time. It’s probably the thing we spend more time with above anything else. In C# 2.0 many new features for string manipulation has been added, so I’ll dig into some of those.
String.ToLowerInvariant/String.ToUpperInvariant
These are two new ways of turning a string into pure lowercased or uppercased characters, but add an invariant culture as IFormatProvider. If you are used to ToLower and ToUpper then you should use the new ones.
string foo = "hello";
foo = foo.ToUpperInvariant();
When comparing two strings in a case-insensitive way, you should uppercase them instead of lowercase. The ToUpperInvariant method performs better than ToLowerInvariant.
string foo1 = "hello";
string foo2 = "HeLLo";
if (foo1.ToUpperInvariant() == foo2.ToUpperInvariant())
{
DoSomething();
}
Read more about ToLowerInvariant and ToUpperInvariant on MSDN.
String.Contains
Visual Basic has had this method for many years, but it was called InStr.
string foo = "hello";
bool test = foo.Contains("he");
If the string "he" is contained within foo, then it return true. It is case-sensitive, so you should uppercase both string if you want a case-insensitive comparison.
string foo = "HeLLo";
bool test = foo.ToUpperInvariant().Contains("he".ToUpperInvariant());
Read more about the Contains method on MSDN
String.Equals
This method compares two strings and returns true if they are the same. It is overloaded and lets you decide if you want a case-sensitive or case-insensitive comparison.
Here is a case-sensitive comparision:
string foo = "hello";
bool test = foo.Equals("hello");
And here it is in a case-insensitive version:
string foo = "hello";
bool test = foo.Equals("hello", StringComparison.OrdinalIgnoreCase);
Read more about the Equals method on MSDN