Tags

    C# Extension Method: ToPascalCase

    Comments

    A function to convert some text to Pascal case always seems to come in handy when writing code generators. So here is a possible implementation:

    using System.Text;
    using System.Text.RegularExpressions;
    
    public static class StringExtensions
    {
        public static string Capatalize(this string text)
        {
            if(string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
    
            int index = 0;
            while(index < text.Length)
            {
                if(!char.IsDigit(text, index))
                {
                    break;
                }
                index++;
            }
    
            if(index < text.Length)
            {
                return string.Format(@"{0}{1}", text.Substring(0, index + 1).ToUpper(), text.Substring(index + 1));
            }
    
            return text;
        }
    
        public static string ToPascalCase(this string text)
        {
            if(string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
    
            var sb = new StringBuilder();
            bool firstWord = true;
            foreach(object match in Regex.Matches(text, "[A-Za-z0-9]+"))
            {
                if(firstWord)
                {
                    sb.Append(match.ToString().Capatalize());
                    firstWord = false;
                }
                else
                {
                    sb.Append(match.ToString().Capatalize());
                }
            }
            return sb.ToString();
        }
    }