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 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
[quoted text clipped - 8 lines]
> 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];

Signature
.NET 2.0 for Delphi Programmers www.midnightbeach.com/.net
Delphi skills make .NET easy to learn In print, in stores.