2

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

5
  • You're probably going to have to do it manually, or use reflection to accomplish this. Have you considered using an enum instead? It would achieve your goal in a simpler manner. Commented Feb 8, 2022 at 23:23
  • smells like XY problem - why do you need to do this? Commented Feb 8, 2022 at 23:29
  • start here learn.microsoft.com/en-us/dotnet/api/… Commented Feb 8, 2022 at 23:30
  • This is a bad idea. If you put it in a list it's not const anymore. And you would have to access them by index which is bad for readability. Commented Feb 8, 2022 at 23:52
  • Keep them in a list to start with, and make those fields into read only properties that pull from the list Commented Feb 9, 2022 at 0:07

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

But, if I add things to Permission class then I have to update my List as well, trying to avoid that.
Why do you need to keep 2 copies? It doesn't make any sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.