C#C
C#4y ago
Connor

How to convert this method into a generic one?

    private List<string> GetEnumNamesCorrected()
    {
        var correctedNames = new List<string>();
        foreach (var enumName in Enum.GetNames(typeof(ManagerType)))
        {
            var wordsInType = 
                Regex.Matches(enumName.ToString(), @"([A-Z][a-z]+)")
                    .Cast<Match>()
                    .Select(m => m.Value);

            var withSpaces = string.Join(" ", wordsInType);
            correctedNames.Add(withSpaces);
        }
        return correctedNames;
    } // Outpets new() { "Human Resources", "General Manager" } just converts to string and adds space at Capital letters
    public enum ManagerType
    {
        HumanResources,
        GeneralManager
    }

I want to be able to do ManagerType.GetEnumNamesCorrected(), as well as with all my other enums. I've come up with this sudo code but it doesn't work
    public static class ExtensionMethods
    {
        public static List<string> GetEnumNamesCorrected<T>(this T enu) where T : Enum
        {
            var correctedNames = new List<string>();
            foreach (var enumName in Enum.GetNames(typeof(enu))) // this is an error
            {
                var wordsInType =
                    Regex.Matches(enumName.ToString(), @"([A-Z][a-z]+)")
                        .Cast<Match>()
                        .Select(m => m.Value);

                var withSpaces = string.Join(" ", wordsInType);
                correctedNames.Add(withSpaces);
            }
            return correctedNames;
        }
    }
Was this page helpful?