Get name of Enum instance
You don't need reflection. You just need to call .ToString()
.
myEnumInstance.ToString();
which will output "ValueTwo"
;
However, if you insist on using reflection, the following example works just fine:
var myClassInstance = new MyClass();
myClassInstance.GetType()
.GetField("myEnumInstance")
.GetValue(myClassInstance);
public enum MyEnum
{
ValueOne = 1,
ValueTwo = 2,
ValueThree = 3
}
public class MyClass
{
public MyEnum myEnumInstance = MyEnum.ValueTwo;
}
Note that in C#6 you can also use nameof
for some strongly-typed syntactic sugar:
myClassInstance.GetType()
.GetField(nameof(myEnumInstance))
.GetValue(myClassInstance);
If you are STILL not able to access the field, it is because it is not public as described in your sample code, in which you'd need to pass in the appropriate binding flags.
myClassInstance
.GetType()
.GetField(nameof(myEnumInstance),
BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance)
.GetValue(myClassInstance);
Keith M
I'm a paid professional programmer who knows a variety of languages. I mostly work on projects for fun in my spare time.
Updated on June 30, 2022Comments
-
Keith M almost 2 years
Say I have this enum:
public enum MyEnum{ ValueOne = 1, ValueTwo = 2, ValueThree = 3 }
And then this field/variable:
public MyEnum myEnumInstance = MyEnum.ValueTwo;
I need to get the
name
ofmyEnumInstance
via reflection from another class.I tried:
myClassInstance.GetType().GetField("myEnumInstance").GetValue(myClassInstance)
Which always returns
ValueOne
, no matter whatmyEnumInstance
is set to.How can I get the string value/name of the enum field via reflection?
-
Keith M about 8 yearsI edited the question to add that I'm accessing this from another class. The way I'm doing this requires reflection. Trust me, I would do
myEnumInstance.ToString();
if it was that simple :) -
NStuke about 8 yearsYou should still be able to call
myClassInstance.myEnumInstance.ToString()
even given your edit? -
David L about 8 years@KeithM NStuke should be correct based on your edit. You can still call
.ToString()
.