How do I create a C# array using Reflection and only type info?

C#ArraysReflectionConstructor

C# Problem Overview


I can't figure out how to make this work:

object x = new Int32[7];
Type t = x.GetType();

// now forget about x, and just use t from here.

// attempt1 
object y1 = Activator.CreateInstance(t); // fails with exception

// attempt2
object y2 = Array.CreateInstance(t, 7);  // creates an array of type Int32[][] ! wrong

What's the secret sauce? I can make the second one work if I can get the type of the elements of the array, but I haven't figured that one out either.

C# Solutions


Solution 1 - C#

You need Type.GetElementType() to get the non-array type:

object x = new Int32[7];
Type t = x.GetType();
object y = Array.CreateInstance(t.GetElementType(), 7);

Alternatively, if you can get the type of the element directly, use that:

Type t = typeof(int);
object y = Array.CreateInstance(t, 7);

Basically, Array.CreateInstance needs the element type of the array to create, not the final array type.

Solution 2 - C#

Just to add to Jon's answer. The reason attempt 1 fails is because there's no default constructor for Int32[]. You need to supply a length. If you use the overload, which takes an array of arguments it will work:

// attempt1 
object y1 = Activator.CreateInstance(t, new object[] { 1 }); // Length 1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark LakataView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Brian RasmussenView Answer on Stackoverflow