2009-01-29

Proper Case Or Title Case

In VB6 there was a function called StrConv which we were using to convert a string to Proper Case or Title Case, but there is no direct equivalent in .NET. Yes, we can still use this function in vb.net but it's not a .NET way. I mean, StrConv cannot be used in C# directly. To use it in C# we need to add the reference of Microsoft.VisualBasic.Compatibility.dll. And people will not like to do so just to use a single function of that library.

Some people write their own function to achieve the functionality. They first convert all the letters of the string to lowercase and then loop through all the words and capitalize the first letter of each word of the string. I am not in favor of this approach. I don't like to write long code just to achieve a small functionality. I always look for shortcuts.

Though there is not direct equivalent for StrConv in .NET, .NET provides us System.Globalization.TextInfo class to overcome the problem. We can use ToTitleCase function of TextInfo class to convert the string in proper case.

I have written a small function to do the work.

Public Function ToProperCase( _
ByVal source As String _
) As String

source = source.ToLower
Return Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(source)
End Function
Usage:
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click

MessageBox.Show(ToProperCase("HELLO WORLD!"))
End Sub
If you want to use ToProperCase() function like this...

Dim str As String = "HELLO WORLD!"
str = str.ToProperCase()
...then you need to use a concept called Extension Methods. Here it goes:

Module ExtensionMethods

_
Public Function ToProperCase( _
ByVal source As String _
) As String

source = source.ToLower
Return Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(source)
End Function

End Module'

No comments: