As you most of you already aware, there are ToLower() and
ToUpper() methods available for String class in C#, but there is no method to
convert a string to ‘Title Case’.
We can implement this conversion with the help of TextInfo
class which has a ToTitleCase method, but you can’t create a new instance of
the TextInfo type as there is no public constructor available. Instead you
will need to first create a new CultureInfo object. To create a new CultureInfo object you can either use hard-coded culture or you can use the current culture of the executing
thread as:
var
cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
That way, if you don’t care about the culture info you’re
using, you will just default to whatever culture info your current thread is
using, much cleaner than the alternative!
Here I'm writing extension method of String named ToTitleCase, in class StringExtension, I have created three extension method, one with current
culture info, and two overloaded method, first takes Culture name as parameter
and another takes CultureInfo as parameter.
public static class StringExtension
{
/// <summary>
/// Use the current culture
info
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static String ToTitleCase(this
String value)
{
var cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
return
cultureInfo.TextInfo.ToTitleCase(value.ToLower());
}
/// <summary>
/// Overload method with
the specified culture info name
/// </summary>
/// <param name="value"></param>
/// <param name="cultureInfoName"></param>
/// <returns></returns>
public static String ToTitleCase(this
String value, String
cultureInfoName)
{
var cultureInfo = new System.Globalization.CultureInfo(cultureInfoName);
return
cultureInfo.TextInfo.ToTitleCase(value.ToLower());
}
/// <summary>
/// Overload method with
the specified culture info
/// </summary>
/// <param name="value"></param>
/// <param name="cultureInfo"></param>
/// <returns></returns>
public static String ToTitleCase(this
String value, System.Globalization.CultureInfo cultureInfo)
{
return
cultureInfo.TextInfo.ToTitleCase(value.ToLower());
}
}
You can use this extension with same as ToLower, ToUpper
etc.
In the remarks of TextInfo.ToTitleCase method in the MSDN
page it is defined that the method doesn’t provide proper casing to convert
a word that is entirely uppercase, such as an acronym. That's why I have used
the ToLower() method in each of the above extension methods.
Cheers Guyz!!!!!!!!
Comments
Post a Comment