About Me 👈

Capitalizing the First Character in a String with C Sharp

How to capitalize the first character in a string with C#.

csharptutorial

Created on December 20, 2019. Last updated on December 20, 2019.

Capitalizing the first character in a string with C# involves handling a couple cases:

  1. If the input string is null or empty, return it (garbage in, garbage out).
  2. Otherwise, you know, do the thing.

Here's the code:

public static string CapitalizeFirstCharacter(string str)
{
    if (string.IsNullOrEmpty(str)) return str;

    var chars = str.ToCharArray();
    chars[0] = char.ToUpper(chars[0]);
    return new string(chars);
}

This is a public static function that ought to go in a static class, since no instantiation should be needed to use it.

By the way, there are other ways to achieve the same result, although this approach is terse and fast. The speed is on account of operating on a character array instead of applying feature-equivalent string operations.