As developers, time to time we have to deal with text cases in our code.
To my surprise, I didn’t find this same level of support in WFP/Silverlight. Granted, you can mark your <TextBox> with CharacterCasing=”Upper” or “Lower”. But no support for Title Case!!!. And no support for other controls, like TextBlock, etc. !
But we play with text cases not only for output. Traditionally some of us do case transformations for case-insensitive compassion, which is wrong on so many levels:
First of all, even if you have to use ToLower or ToUpper method, it is a good practice to pass CultureInfo as a parameter. Your server may use one culture, but web request may come with a different culture! By passing culture info into formatting and case transforming methods you ensure that your customers will see what they suppose to see:
Don’t get me wrong; this code is still bad – it is just marginally better than before. First of all, what if arg is null? Or str is null? Sure, we can add those checks, but it will make the code even less readable.
Fortunately, NET provides us with the nice alternative: System.String static methods like Equals, Compare, Format, Join, etc.
So our code can look like this:
Actually it even runs significantly faster!!! And it is smart enough to take care of special characters !!!:
But if you want to be 100% sure that you are producing the right result, don’t rely on System.String.Equals function – use System.String.Compare instead. It took Culture as a parameter and guaranteed to perform checks according to provided culture rules.
CultureInfo is a fascinating class; it provides you with all information necessary to display your information correctly in different cultures and languages.
Here is the hidden gem that I found that can be used to To Display Dynamic String In Title Case:
So, bottom line:
- Use static methods of the System.String with Culture information for string comparison.
- Use CultureInfo’s methods to UpperCase, LowerCase and TitleCase conversions.