Is there a way to set a single value in an array property via reflection in c#?
My property is defined like this:
double[] Thresholds { get; set; }
For “normal” properties I use this code to set it via reflection:
PropertyInfo pi = myObject.GetType().GetProperty(nameOfPropertyToSet);
pi.SetValue(myObject, Convert.ChangeType(valueToSet, pi.PropertyType), null);
How would I have to change this code to set the value in an array property at an arbitrary position?
Thanks!
BTW: I tried to use the index parameter, but that seems only to work for indexed properties, not properties that are arrays…
When you do:
that is semantically equivalent to:
which means you don’t want a
SetValueat all; rather, you want to useGetValueto obtain the array, and then mutate the array. If the type is known to bedouble[], then:otherwise perhaps the non-generic
IListapproach (since arrays implementIList):If it is a multi-dimensional array, you’ll have to use
Arrayin place ofIList.