Reputation: 315
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 ?
Upvotes: 5
Views: 8331
Reputation: 21742
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);
Upvotes: 2
Reputation: 7930
Try use of class Enum
LevelEnum s = (LevelEnum)Enum.Parse(typeof(LevelEnum), "CDD");
Upvotes: 5
Reputation: 101140
public class MyObject
{
public LevelEnum MyValue {get;set,};
}
var obj = new MyObject();
obj.GetType().GetProperty("MyValue").SetValue(LevelEnum.CDD, null);
Upvotes: 3