How do I instantiate an array property using Reflection based on the code below?
public class Foo
{
public Foo()
{
foreach(var property in GetType().GetProperties())
{
if (property.PropertyType.IsArray)
{
// the line below creates a 2D array of type Bar. How to fix?
var array = Array.CreateInstance(property.PropertyType, 0);
property.SetValue(this, array, null);
}
}
}
public Bar[] Bars {get;set;}
}
public class Bar
{
public string Name {get;set;}
}
The first parameter of
Array.CreateInstance
expects the element type of the array. You pass the entire property type, which is, as you have just found out by checkingproperty.PropertyType.IsArray
, an array type (specifically,Bar[]
- i.e. an array ofBar
elements).To get the element type of an array type, use its
GetElementType
method:I suppose you will replace the zero passed to the second argument with a higher number when required, unless you actually want only empty arrays.