C# Reflection – set object enum property value

using C# Reflection can convert DataTable to Object easily.
However, it may be have some problems when converting enum which is special, we don’t know enum type and enum type should get from reflection.

Here is code sample for c# enum property covert.

1
2
3
4
5
6
7
8
var a =  new YourObject(); 
PropertyInfo propertyInfo = a.GetType().GetProperty(s);
if (propertyInfo.PropertyType.IsEnum)
  {
    propertyInfo.SetValue(a, Convert.ChangeType(Enum.Parse(propertyInfo.PropertyType, dr[index++].ToString()), propertyInfo.PropertyType), null);
  }
 else
    propertyInfo.SetValue(a, Convert.ChangeType(dr[index++].ToString(), propertyInfo.PropertyType), null);
This entry was posted in C#. Bookmark the permalink.