tRuEsAtM
tRuEsAtM

Reputation: 3668

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

Upvotes: 2

Views: 2793

Answers (2)

Serge
Serge

Reputation: 43900

Instead of string, better to use KeyValuePair, this way constants can be used the same way as enumerations.

List<KeyValuePair<string,string>> consts = typeof(Permission).GetFields()
.Select(p => new KeyValuePair<string,string> ( p.Name, (string)p.GetValue(null))).ToList();

result

AccessRightFormAdmin    TEST1
AccessRightExperimental TEST2

Upvotes: 1

David L
David L

Reputation: 33833

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.

Upvotes: 6

Related Questions