As you most likely know already, there are ToLower() and ToUp­per() meth­ods on the String class in C#, but a method to con­vert a string to ‘Title Case’ is sadly missing.

Sup­port for this use­ful con­ver­sion exists in the Tex­tInfo class which has a ToTi­tle­Case method, but you can’t instan­ti­ate a new instance of the Tex­tInfo type as there is no pub­lic con­struc­tor. Instead you will need to first cre­ate a new Cul­ture­Info object:

var str = "wAr AnD peaCE";
var textInfo = new CultureInfo("en-US").TextInfo;
var titleCaseStr = textInfo.ToTitleCase(str);
Console.WriteLine(titleCaseStr);
/* this outputs
War And Peace
*/

See­ing as the Cul­ture­Info class doesn’t have a parameter-less con­struc­tor, it means if you wish to do the above you have to pro­vide a ‘default’ cul­ture. Instead of hard-coding a default cul­ture in your code, I’d rec­om­mend using the cur­rent cul­ture of the exe­cut­ing thread instead:

var cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;

That way, if you don’t care about the cul­ture info you’re using, you will just default to what­ever cul­ture info your cur­rent thread is using, much cleaner than the alternative!

Bet­ter still, if you’re gonna be need­ing title case con­ver­sion often, why not just add some exten­sion meth­ods to the Sting type:

public static class StringExtension
{
    /// <summary>
    /// Use the current thread's culture info for conversion
    /// </summary>
    public static string ToTitleCase(this string str)
    {
        var cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
        return cultureInfo.TextInfo.ToTitleCase(str.ToLower());
    }

    /// <summary>
    /// Overload which uses the culture info with the specified name
    /// </summary>
    public static string ToTitleCase(this string str, string cultureInfoName)
    {
        var cultureInfo = new CultureInfo(cultureInfoName);
        return cultureInfo.TextInfo.ToTitleCase(str.ToLower());
    }

    /// <summary>
    /// Overload which uses the specified culture info
    /// </summary>
    public static string ToTitleCase(this string str, CultureInfo cultureInfo)
    {
        return cultureInfo.TextInfo.ToTitleCase(str.ToLower());
    }
}

You may have noticed from the remarks in the MSDN page for the TextInfo.ToTitleCase method that the method doesn’t pro­vide proper cas­ing to con­vert a word that is entirely upper­case, such as an acronym.

It’s for this rea­son that I have added the ToLower() call in each of the above exten­sion methods.

Share

Leave a Reply