create the array using reflection

G

Guest

I have a type of System.Type. It indicates an primitive type such as Int32. I
try to use the following code to create an array

Type arrayType = type.MakeArrayType(5);
object objArray = Activator.CreateInstance(arrayType);

but I got the following error:
{"No parameterless constructor defined for this object."}

Apparently, this is caused by the fact that the array type does not have a
default constructor.
How do I create the array using reflection?
 
J

Jon Shemitz

Roy said:
I have a type of System.Type. It indicates an primitive type such as Int32. I
try to use the following code to create an array

Type arrayType = type.MakeArrayType(5);
object objArray = Activator.CreateInstance(arrayType);

but I got the following error:
{"No parameterless constructor defined for this object."}

Apparently, this is caused by the fact that the array type does not have a
default constructor.
How do I create the array using reflection?

I wrote the following app to examine the array's constructors:

using System;
using System.Reflection;

namespace NewArray
{
class Program
{
static void Main(string[] args)
{
Type IntType = typeof(int);
Type IntArrayType = IntType.MakeArrayType(5);
ConstructorInfo[] Constructors = IntArrayType.GetConstructors();
foreach (ConstructorInfo Constructor in Constructors)
{
ParameterInfo[] Parameters = Constructor.GetParameters();
string[] Types = new string[Parameters.Length];
for (int Index = 0; Index < Parameters.Length; Index++)
Types[Index] = Parameters[Index].ParameterType.Name;
Console.WriteLine("({0})", String.Join(", ", Types));
}
Console.ReadLine();
}
}
}

//

It gives the following output:

(Int32, Int32, Int32, Int32, Int32)
(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32)

//

That is, you can pass either five lengths (one for each dimension) or
five pairs of start/stop indices. Thus,

int[, , , ,] A = (int[, , , ,])
Activator.CreateInstance(IntArrayType, 3, 3, 3, 3, 3);

is exactly analagous to (but slower than)

int[, , , ,] B = new int[3, 3, 3, 3, 3];
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top