It’s a requirement (or nicety) at times to have words like names be formatted in Title or Proper case. Formatting text to Upper or Lowercase using the String class in C# is easy and you would think that the String class would also have a ToProper() or ToTitleCase() function but alas it does not.
Never fear though, the TextInfo class does have this functionality and is found in the System.Globalization namespace.
Read on for more on what you can do with TextInfo to Title or Proper case your text.
So what is Title or Proper case.
Well let’s take a name for example ‘john smith’. In Title (or Proper and I will just call it Title from here on in) this would be ‘John Smith’. The first letters are in Upper Case.
To achieve this we need to use the TextInfo class and we must also specify culture information.
The first things we will need are our namespaces which are:
We need the reference to System.Threading to get the CultureInfo for the current thread and from that we can get the TextInfo class. as shown below:
Once we have that we just need to call the ToTitleCase method on the TextInfo instance passing in the text we want to process.
One of the great things about this is that it works on hyphenated names as well.
So passing in my surname of ‘coenen-eyre’ will convert my name to ‘Coenen-Eyre’ which is what we want.
All in all this is a handy little class to have around if only for Title casing text.