Search code examples
c#constants

Adding all string constants from a class to a List of string constants in C#


I have a class,

        public static class Permissions
        {
            public const string AccessRightFormAdmin = "TEST1";
            public const string AccessRightExperimental = "TEST2";
        }

I want to have List<string> myConsts = new List<string>; such that, myConsts contains all the string constants from the Permissions class. How can I achieve this in C#?


Solution

  • If you want to avoid having to manually maintain your myConsts collection, you will have to use reflection.

    public readonly List<string> myConsts = 
        typeof(Permissions)
            .GetFields()
            .Select(x => x.GetValue(null).ToString())
            .ToList();
    

    This looks at the Permissions type, selects all public fields, then pulls the values from those FieldInfo into a new collection.