Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate an Enum array via reflection

I have a method that reads some XML and populates an object. This is done via reflection based on the element names in the XML mathing the property names on the object. This works for basic object types but i am struggling with enum arrays.

So I have a PropertyInfo object (lets call it property) for my enum array property and I have a string value (lets call it value) containing comma separated numbers representing the enum values (e.g. "1,3,5").

I have tried:

property.SetValue(this, value.Split(',').Select(i => int.Parse(i)).ToArray(), null);

and

property.SetValue(this, value.Split(',').Select(i => Enum.ToObject(property.PropertyType.GetElementType(), int.Parse(i))).ToArray(), null);

But no joy. In the first code example the result of the Select.ToArray is an int[] which then throws a parse error. Similar case with the second but the Select.ToArray returns an object[] and again throws a parse error.

I want to write this as if the enum type is unknown.

Any ideas?

like image 882
CeejeeB Avatar asked Jul 03 '26 10:07

CeejeeB


1 Answers

try this:

// create the enum values as object[]
var values = value.Split(',')
  .Select(i => Enum.Parse(property.PropertyType.GetElementType(), i))
  .ToArray()

// create array of correct type
Array array = (Array)Activator.CreateInstance(property.PropertyType, values.Length);

// copy the object values to the array
int i = 0;
foreach(var value in values)
{
  array.SetValue(value, i++);
}

// set the property
property.SetValue(this, array, null)

There might be a simpler way, but the key is that you create an array of the correct type.

like image 93
Stefan Steinegger Avatar answered Jul 04 '26 22:07

Stefan Steinegger