Sunday, June 16, 2019

c# - 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);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...