BestPractice - Transform first character of a string into lower case

Just in case it helps anybody who happens to stumble across this answer.

I think this would be best as an extension method, then you can call it with yourString.FirstCharacterToLower();

public static class StringExtensions
{
    public static string FirstCharacterToLower(this string str)
    {
        if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
        {
            return str;
        }

        return Char.ToLowerInvariant(str[0]) + str.Substring(1);
    }
}

I would use simple concatenation:

Char.ToLowerInvariant(name[0]) + name.Substring(1)

The first solution is not optimized because string.Format is slow and you don't need it if you have a format that will never change. It also generates an extra string to covert the letter to lowercase, which is not needed.

The approach with "+ 32" is ugly / not maintainable as it requires knowledge of ASCII character value offsets. It will also generate incorrect output with Unicode data and ASCII symbol characters.


Depending on the situation, a little defensive programming might be desirable:

public static string FirstCharacterToLower(string str)
{
    if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
        return str;

    return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}

The if statement also prevents a new string from being built if it's not going to be changed anyway. You might want to have the method fail on null input instead, and throw an ArgumentNullException.

As people have mentioned, using String.Format for this is overkill.


The fastest solution I know without abusing c#:

public static string LowerCaseFirstLetter(string value)
{
    if (value?.Length > 0)
    {
        var letters = value.ToCharArray();
        letters[0] = char.ToLowerInvariant(letters[0]);
        return new string(letters);
    }
    return value;
}

Tags:

C#

.Net

String