0

I have a class with const strings,
is there any way to get all const strings of these class to a List ?

public class Permissions
{
public const string AccessHomePage = "AccessHomePage";
public const string AccessAdminPage = "AccessAdminPage";
...
}

To add an admin user all permission at once would be easier
to get a list directy of all strings in the class...

List<string> allPermissions =

Would be really nice...

Fabian
  • 1,130
  • 9
  • 25
  • You can use reflection to get all constant fields in your class – Neistow Jul 08 '21 at 06:42
  • 2
    There is no straight forward way to achieve this. You need to use reflection. If you can modify this class then you should expose a property from this class with a list of all the strings. – Chetan Jul 08 '21 at 06:43
  • 1
    Maybe an enum with flags attribute would be a better solution? If you really want to use string constants, try https://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection – SomeBody Jul 08 '21 at 06:45
  • @SomeBody yep this would be the right so to look up, coudn't find it since i wasn't aware of reflections... – Fabian Jul 08 '21 at 07:00
  • 1
    NB: If your string values are always equal to the field name, you might as well use `public const string AccessHomePage = nameof(AccessHomePage);`, lest they might get "out of sync". – Heinzi Jul 08 '21 at 07:24

1 Answers1

1

Maybe

Given

public class Permissions
{
   public const string AccessHomePage = "AccessHomePage";
   public const string AccessAdminPage = "AccessAdminPage";
}

Example

private static IEnumerable<string> GetConstants<T>()
   => typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
      .Where(x => x.FieldType == typeof(string) && x.IsLiteral && !x.IsInitOnly)
      .Select(x => x.GetValue(null) as string);

Usage

foreach (var item in GetConstants<Permissions>())
   Console.WriteLine(item);

Output

AccessHomePage
AccessAdminPage

Add Pepper and Salt to taste


Explanation

BindingFlags.Public

Specifies that public members are to be included in the search.

BindingFlags.Static

Specifies that static members are to be included in the search.

BindingFlags.FlattenHierarchy

Specifies that public and protected static members up the hierarchy should be returned. Private static members in inherited classes are not returned. Static members include fields, methods, events, and properties. Nested types are not returned.

FieldInfo.IsInitOnly Property

Gets a value indicating whether the field can only be set in the body of the constructor.

FieldInfo.IsLiteral Property

Gets a value indicating whether the value is written at compile time and cannot be changed.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141