To Upper Case First Letter of a String in C#

Oct 28, 2010 Posted by Lara Kannan
Utilize a simple extension method to capitalize the first letter of a string.


public class Program
{
static void Main(string[] args)
{
string s = "toUpperFirstLetter";

// ToUpperFirstLetter is the extension method defined below
Console.WriteLine(s.ToUpperFirstLetter());

// output: ToUpperFirstLetter
Console.ReadLine();
}
}

// string extension class
public static class StringExtension
{
// string extension method ToUpperFirstLetter
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();

// upper case the first char
letters[0] = char.ToUpper(letters[0]);

// return the array made of the new char array
return new string(letters);
}
}


Source : www.codemeit.com
Share
Labels: ,

Post a Comment