What is the difference between ToUpper() and ToUpperInvariant() methods of String class in .Net.

The String class has two methods called ToUpper() and ToUpperInvariant().  What are their differences and when to use which one?

ToUpper() method convert all chars to uppercase by leveraging casing conventions of “current culture”.

ToUpperInvariant() methods does the same job as ToUpper() by leveraging casing convention of “invariant culture”. So it produces the same result for any system regardless of the user’s current culture.  Therefore, when comparing the system identifiers, i.e. file names, paths, etc., normalizing the identifiers with ToUpperInvariant() is the right choice.

So the next question is … What culture does ToUpperInvariant() uses?

Below are the decompiled code of the methods inside System.String class.

public string ToUpper()
      return this.ToUpper(CultureInfo.CurrentCulture);
public string ToUpperInvariant()
      return this.ToUpper(CultureInfo.InvariantCulture);

By the way… What is the InvariantCulture?

The short answer is it is a common culture that can be used regardless of user’s country and language.

The detailed answer is clearly explained in “Using the InvariantCulture Property” and “Performing Culture-Insensitive String Operations”.

To sum up, as a general best practice, ToUpper() should be called when handling user generated strings while ToUpperInvariant should be called when handling system resources such as filenames and uri’s.


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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