Set Enums Using Reflection

How to set Enums using reflection,

In my class are listed:

public enum LevelEnum
    {
        NONE,
        CRF,
        SRS,
        HLD,
        CDD,
        CRS
    };

and at runtime I want to set this enumeration for CDD for ex.

How can i do this?

+5
source share
3 answers
public class MyObject
{
    public LevelEnum MyValue {get;set,};
}


var obj = new MyObject();
obj.GetType().GetProperty("MyValue").SetValue(LevelEnum.CDD, null);
+3
source

Try using the Enum class

LevelEnum s = (LevelEnum)Enum.Parse(typeof(LevelEnum), "CDD");
+4
source
value = (LevelEnum)Enum.Parse(typeof(LevelEnum),"CDD");

So, you simply parse the string corresponding to the value of the enumeration that you want to assign to the variable. This will happen if the string is not a specific member of the enumeration. you can check it withEnum.IsDefined(typeof(LevelEnum),input);

0
source

All Articles