How to set Enums using reflection,
my class have enum :
public enum LevelEnum
{
NONE,
CRF,
SRS,
HLD,
CDD,
CRS
};
and in runtime I want to set that enum to CDD for ex.
How can I do it ?
Try use of class Enum
LevelEnum s = (LevelEnum)Enum.Parse(typeof(LevelEnum), "CDD");
public class MyObject
{
public LevelEnum MyValue {get;set,};
}
var obj = new MyObject();
obj.GetType().GetProperty("MyValue").SetValue(LevelEnum.CDD, null);
value = (LevelEnum)Enum.Parse(typeof(LevelEnum),"CDD");
So basically you just parse the string corresponding to the enum value that you wish to assign to the variable. This will blow if the string is not a defined member of the enum. you can check that with Enum.IsDefined(typeof(LevelEnum),input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With