Dynamically set enum value

I came across code where I needed to populate properties in a class dynamically, in a loop.  It is pretty straight forward if the type is int, string, date, etc.  But when it is an enum, isn’t so easy.  I was able to find a solution using the Enum.Parse function.  Here is some sample code:

    enum AnimalType
    {
        Dog,
        Cat,
        Bird
    }
    class Animal
    {
        public AnimalType AnimalType { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            object target = new Animal ();
            var type = target.GetType();

            foreach (var p in type.GetProperties())
            {
                if (p.PropertyType.BaseType == typeof(Enum))
                {
                    var propType = p.PropertyType;
                    
                    try
                    {
                        var e = Enum.Parse(propType, "Dog");
                        p.SetValue(target, e);
                    }
                    finally
                    {
                    } 
                }
            }
        }
    }

Leave a comment