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.


2 Responses to “Don’t use .ToUpper() or .ToLower()”

  1. Vladimir Georgiev Says:

    Hi, Peter.

    I think it is really great, that you show – every day tasks that can be accomplished more efficiently. Keep up the good work. 🙂

    But …

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

    is very Java like IMHO.

  2. SKJ Says:

    This is simply great ! I was looking for this ..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s