I have a simple Enum
public enum TestEnum
{
TestOne = 3,
TestTwo = 4
}
var testing = TestEnum.TestOne;
And I want to retrieve its value (3) via reflection. Any ideas on how to do this?
I have a simple Enum
public enum TestEnum
{
TestOne = 3,
TestTwo = 4
}
var testing = TestEnum.TestOne;
And I want to retrieve its value (3) via reflection. Any ideas on how to do this?
If you have loaded an assembly in reflection-only context the methods GetValue and GetValues don't work. But we can use another approach:
var val = typeof(MyEnum).GetFields()
.Where(fi => fi.IsLiteral && fi.Name == "TestOne")
.Select(fi => fi.GetRawConstantValue())
.First();
You can use the Gethashkey function to get the value of enum with an unknown type.
Enum.Parse(enumType, enumvalue).GetHashCode();
More details
Getting enum type dynamically
private static Type GetEnumType(string enumName)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var type = assembly.GetType(enumName);
if (type == null)
continue;
if (type.IsEnum)
return type;
}
return null;
}
Reading enum values
Enum.GetValues(enumType);
I hope it helps someone!
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);
}
There must be a motivation to ask a question like this. Here I have one real life scenario with good motivation to do something like this and the solution to this problem.
Motivation
2 assemblies with circular references. One reference is hard reference, i.e. <Reference . . .> tag in project file. And a soft reference in opposite direction. assembly1 must call some object, some method in assembly2. Method's argument is enum
Here is the code that will get enum value. The assembly is already loaded at the time of calling this method because instance of the object containing method already loaded
Solution
internal static object GetEnumValue(string assemblyName, string enumName, string valueName) // we know all these
{
var assembly = Assembly.Load(assemblyName);
var converter = new EnumConverter(assembly.GetType(enumName));
object enumVal = converter.ConvertFromString(valueName);
return enumVal;
}
And the usage
dynamic myInstance = GetInstanceOfKnownObject(.......); // this preloads assembly for first time. All sequential loads are easy
dynamic enumArg = GetEnumValue("assemblyName", "assembly2.namespace1.EnumName", "enumValueName"); // important to load into 'dynamic', not 'object'
myInstance.MyMethod(enumArg);
Bottom line - it is really useful when one assembly has no idea (and can't have knowledge) of the other assembly internals.