0

Is there any way to read the const names into a list?

Example Code

public static class Cars
{
    public const int Length= 10;
    public const int Height= 15;
    public const int Weight = 20;
}
Xyz
  • 5,955
  • 5
  • 40
  • 58
user3635120
  • 73
  • 3
  • 10

2 Answers2

3

You can use reflection like this.

var fields = typeof(Cars)
    .GetFields(BindingFlags.Public | BindingFlags.Static)
    .Select(f => new { Name = f.Name, Value = f.GetValue(null) })
    .ToList();
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67
2

Yes:

typeof(Cars).GetFields(BindingFlags.Instance |BindingFlags.Static | BindingFlags.Public).Select(m => m.Name)
Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
chris
  • 2,541
  • 1
  • 23
  • 40