Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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#?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading