2

This SO post talks about properties however I am trying to get at the constants in the following static class:

public static class SpYtMessageConstants
{
    public const int MSG_NOOP = 1;
    public const int MSG_PING = 2;
}

I want to loop through all the constants and get each value values. This is for a unit test to make sure nobody has added the same value twice.

TheEdge
  • 9,291
  • 15
  • 67
  • 135
  • @HimBromBeere if you look at my original post you will see I reference that exact same post. However it is dealing with properties accessing constants not directly constants as is my case. So it is not a direct answer. – TheEdge Mar 06 '19 at 11:34
  • If you only have read the other answers also and not only the accepted one, you would have got the solution yourself. Anyway here´s another duplicate: https://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection – MakePeaceGreatAgain Mar 06 '19 at 11:38

1 Answers1

1

We want static (and public) fields' (not properties) values which can be set at compile time only (IsLiteral) while not being readonly - IsInitOnly

Object[] values = typeof(SpYtMessageConstants)
  .GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
  .Where(f => f.IsLiteral && !f.IsInitOnly)
  .Select(f => f.GetValue(null))
  .ToArray();

Finally, in your particular case BindingFlags.FlattenHierarchy is redundant, however, it can be useful in case classes are inherited:

public class BaseClass {
  public const int BaseConst = 123;
}

public class DerivedClass : BaseClass {
  public const int DerivedConst = 456;
}

in case BindingFlags.FlattenHierarchy specified both BaseConst and DerivedConst are returned

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215