27 March 2009

C# TextInfo Class, ToTitleCase() Method.

As someone who spent a number of years working with VB6 I still miss a built in function for turning a string to Proper case. string has the ToUpper() and ToLower() static methods which work as you expect but no ToTitleCase or ToProperCase function. (Yes I know that if you are compiling against .Net3.5 you can extend the string type but I am still compiling against .Net2.0 for this project).

So I was looking at the best way to proper case a string today and I found this Microsoft help article. The article points to the TextInfo class and it's ToTitleCase() instance method.

Although you have to go through hoops to get an instance of the TextInfo class (you need to provide details of the culture etc) you can then pass the ToTitleCase() method a string and use the result.

Only what seems to be undocumented is the fact that the string provided to the method has to be lower case. It seems to work on the assumption that it only needs to make the first letter in the word upper case and ignore the remaining characters. Therefore, if you provide an upper case word you get an upper case word back.

I may be alone but I think that is a bit lazy. Whoever, implemented that function should be checking the case of the parameter. I mean to make the function fool proof parameter.ToLower() as the first line of the function would do the trick.

No comments: