I have a simple Enum
public enum TestEnum
{
TestOne = 3,
TestTwo = 4
}
var testing = TestEnum.TestOne;
And I want to retrieve
Get enum int value via reflection using this method
protected static object PropertyValue(object obj, string propertyName)
{
var property = obj.GetType().GetProperty(propertyName);
if(property == null)
throw new Exception($"{propertyName} not found on {obj.GetType().FullName}");
if (property.PropertyType.IsEnum)
return (int) property.GetValue(obj);
return property.GetValue(obj);
}
Why do you need reflection?
int value = (int)TestEnum.TestOne;
Or, if you needed the actual enum object (of type TestEnum) :
MemberInfo[] memberInfos = typeof(MyEnum).GetMembers(BindingFlags.Public | BindingFlags.Static);
string alerta = "";
for (int i = 0; i < memberInfos.Length; i++) {
alerta += memberInfos[i].Name + " - ";
/* alerta += memberInfos[i].GetType().Name + "\n"; */
// the actual enum object (of type MyEnum, above code is of type System.Reflection.RuntimeFieldInfo)
object enumValue = memberInfos[i].GetValue(0);
alerta += enumValue.ToString() + "\n";
}