Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Don’t use .ToUpper() or .ToLower() June 27, 2008

Filed under: .NET Framework,C# — ppetrov @ 11:36 am
Tags: , , ,

I’ve seen on many code snippets and posts an inadequate use of ToUpper() and ToLower() methods of the string class. It’s a well know fact that string is immutable and these methods will return a copy of the original string.

A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

If you need to compare two strings ignoring the case, we must use the static method Equals()


string.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase)

or the instance one.


"abc".Equals("ABC", StringComparison.OrdinalIgnoreCase)

StartsWith(), EndsWith(), IndexOf() etc – all of these methods provide a way to specify the
StringComparison type.
An interesting method is Contains(). There’s no way to specify the StringComparison type or to say ignoreCase = true.
Actually it’s an alias for IndexOf(). In Reflector we can see the following implementation

public bool Contains(string value)
{
    return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

To fill this gap I’ve decided to write an extension method with an additional parameter

        public static bool Contains(this string original, string value, StringComparison comparisionType)
        {
            return original.IndexOf(value, comparisionType) >= 0;
        }

Now we can use it like this

"abc".Contains("AB", StringComparison.OrdinalIgnoreCase)

I think it’s a useful method so I’ll post this extension method as a separate post.