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.
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)));
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")
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With