4

I want to loop all the constant variable from a static class. For example

public class SiteDetails
{
    public const string SD_MAIN_TRUST = "MainTrust";
    public const string SD_MAIN_COLLEGE = "MainCollege";
}

I want to read constants one by one to check for match.

Mo Patel
  • 2,321
  • 4
  • 22
  • 37
Geeth
  • 5,282
  • 21
  • 82
  • 133
  • 3
    Are all the constants effectively related? Sounds like you should use an enum instead. – Jon Skeet Jan 20 '14 at 09:54
  • See: http://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection/34228649#34228649 – bytedev Dec 15 '15 at 16:19

2 Answers2

10

Get all public static fields of your type:

Type type = typeof(SiteDetails);
var flags = BindingFlags.Static | BindingFlags.Public;
var fields = type.GetFields(flags); // that will return all fields of any type

You can add IsLiteral filtering if you want to check only constants.

var fields = type.GetFields(flags).Where(f => f.IsLiteral);

Then check if value of any field equals to your value:

string value = "MainCollege"; // your value
bool match = fields.Any(f => value.Equals(f.GetValue(null)));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Getfields() is not returning the constants. I want to read all the constants one by one. – Geeth Jan 22 '14 at 06:24
  • @Nathiya I don't think you have tried my code. You have static literal fields, which should be read with GetFields() method – Sergey Berezovskiy Jan 22 '14 at 06:31
  • i have tried your code just now it is giving zero fields. var flags = BindingFlags.Static | BindingFlags.Public; var field1s = classType.GetFields(flags); – Geeth Jan 22 '14 at 06:42
  • @Nathiya just verified - it gives me two fields `SD_MAIN_TRUST` and `SD_MAIN_COLLEGE`. Make sure you are using exactly same code as I provided. Also make sure your real class has name `SiteDetails` and it really contains fields. – Sergey Berezovskiy Jan 22 '14 at 06:55
  • Now i am getting the result after including BindingFlags.Instance im getting the result. In order to check the fields how to get all the fields using loop? – Geeth Jan 22 '14 at 07:17
  • @Nathiya if you are getting results with BindingFlags.Instance then your code differs from question. Constants are static. Also I don't understand why you need explicit loop if you want to check for match. But of course you can `foreach(FieldInfo field in fields) { ... }` – Sergey Berezovskiy Jan 22 '14 at 07:20
4

You can enumerate constants by using Linq:

  foreach(FieldInfo info in typeof(SiteDetails).GetFields().Where(x => x.IsStatic && x.IsLiteral)) {
    // info is the constant description with
    // info.Name       - constant's name  (e.g. "SD_MAIN_TRUST")
    // info.GetValue() - constant's value (e.g. "MainTrust")
    ...
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215