c# - Get name of Enum instance -


say have enum:

public enum myenum{     valueone = 1,     valuetwo = 2,     valuethree = 3 } 

and field/variable:

public myenum myenuminstance = myenum.valuetwo; 

i need name of myenuminstance via reflection from class.

i tried:

myclassinstance.gettype().getfield("myenuminstance").getvalue(myclassinstance) 

which returns valueone, no matter myenuminstance set to.

how can string value/name of enum field via reflection?

you don't need reflection. need call .tostring().

myenuminstance.tostring(); 

which output "valuetwo";

however, if insist on using reflection, following example works 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 in c#6 can use nameof strongly-typed syntactic sugar:

myclassinstance.gettype()                .getfield(nameof(myenuminstance))                .getvalue(myclassinstance); 

if still not able access field, because not public described in sample code, in you'd need pass in appropriate binding flags.

myclassinstance     .gettype()     .getfield(nameof(myenuminstance),          bindingflags.nonpublic | bindingflags.getfield | bindingflags.instance)     .getvalue(myclassinstance); 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -