Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop all the constants in a class [duplicate]

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.

like image 578
Geeth Avatar asked Dec 08 '22 10:12

Geeth


2 Answers

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)));
like image 104
Sergey Berezovskiy Avatar answered Dec 11 '22 08:12

Sergey Berezovskiy


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")
    ...
  }
like image 32
Dmitry Bychenko Avatar answered Dec 11 '22 07:12

Dmitry Bychenko