Skip to content

[API Proposal]: string.ToTitleCase() extension method(s) #72269

@SteveDesmond-ca

Description

@SteveDesmond-ca

Background and motivation

I often find myself needing to title case strings, and the current API for doing so isn't so intuitive. As the action is being performed on the string, it seems more idiomatic for a .ToTitleCase() method to happen on the string itself.

API Proposal

public static class StringExtensions
{
    public static string ToTitleCase(this string str) => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
    public static string ToTitleCase(this string str, CultureInfo culture) => culture.TextInfo.ToTitleCase(str);
}

API Usage

var bookName = "a tale of two cities";
var title = bookName.ToTitleCase();

var eh = new CultureInfo("en-CA");
var songName = "my favourite chords";
var title = songName.ToTitleCase(eh);

Alternative Designs

This could also be done as a single method with an optional culture parameter:

public static string ToTitleCase(this string str, CultureInfo? culture = null)
    => (culture ?? CultureInfo.CurrentCulture).TextInfo.ToTitleCase(str);

but I think the overload is probably a better choice, and aligns more with existing .NET API designs.

The method could also be called .ToTitle() to better align with .ToUpper() and ToLower(). This may also involve adding a .ToTitleInvariant() variant for consistency.

Risks

There's a chance that using the current culture as the default leads to undesired results based on incorrect developer assumptions, which may not be present when explicitly choosing a CultureInfo/TextInfo. I think this is a similar risk to how time zones are dealt with: certain actions use the host's current time zone by default.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Globalizationneeds-author-actionAn issue or pull request that requires more info or actions from the author.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions