Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set Enums using reflection

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 ?

like image 446
Yasser Avatar asked Aug 10 '11 11:08

Yasser


3 Answers

Try use of class Enum

LevelEnum s = (LevelEnum)Enum.Parse(typeof(LevelEnum), "CDD");
like image 75
Jan Remunda Avatar answered Oct 13 '22 02:10

Jan Remunda


public class MyObject
{
    public LevelEnum MyValue {get;set,};
}


var obj = new MyObject();
obj.GetType().GetProperty("MyValue").SetValue(LevelEnum.CDD, null);
like image 36
jgauffin Avatar answered Oct 13 '22 02:10

jgauffin


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

like image 40
Rune FS Avatar answered Oct 13 '22 02:10

Rune FS