Array made by Reflection doesn't act normally

Apparently making an array through reflection like this:

typeof(object).MakeArrayType()

Makes an array that doesn’t function quite the same as doing this:

new object[0]

Long story short, I’m reading in arrays of all different data types from a file and I realized that the array created by MakeArrayType could not be casted to be an IEnumerable object. However, a normally made array could.

Here’s an example of this in action:


object byReflection = (typeof(int)).MakeArrayType();
int[] normal = new int[0];
Debug.Log(byReflection);
Debug.Log(normal);


IEnumerable convertTo;
try
{
	convertTo = (IEnumerable)byReflection;
	Debug.Log(convertTo);
}
catch(Exception e)
{
	Debug.Log(e.Message);
}

`
try
{
	convertTo = (IEnumerable)normal;
	Debug.Log(convertTo);
}
catch(Exception e)
{
	Debug.Log(e.Message);
}
`

Any idea on why this is happening and/or how I can make an array given I have the Type object for it (or its element type)?

MakeArrayType gives you the System.Type object for that type but not the type itself. So you actually didn’t created an array. you just get the reference to the Type-Object that is describing the type. That object doesn’t support IEnumerable :wink: Don’t you ask yourself where you should specify the size of the array?

I don’t worked that much with reflection but you should get the constructor of your array type and call it (GetConstructor()).

Another way would be to use the System.Array.CreateInstance(). You have to supply only the element type to this function and of course the size.