HelterSkelter HelterSkelter - 2 months ago 9
C# Question

GetConstructors doesn't find the declared constructor

I'm experimenting with

System.Type
. In the following code, I used
GetConstructors
on an array type:

using System;
using System.Reflection;

class Animal
{
public Animal (string s)
{
Console.WriteLine(s);
}
}

class Test
{
public static void Main()
{
Type AnimalArrayType = typeof(Animal).MakeArrayType();
Console.WriteLine(AnimalArrayType.GetConstructors()[0]);
}
}


The output is:
Void .ctor(Int32)
. Why? Shouldn't it be
Void .ctor(System.string)
?

Answer

You called .MakeArrayType() so you're doing reflection on an array of Animal, not Animal itself. If you remove that, you'll get the constructor you expected.

Type AnimalArrayType = typeof(Animal);
Console.WriteLine(AnimalArrayType.GetConstructors()[0]);

If you wanted to get the element type of an array type, you can do it like this.

Type AnimalArrayType = typeof(Animal[]);
Console.WriteLine(AnimalArrayType.GetElementType().GetConstructors()[0]);

In order to construct an array of the desired size, you can use this.

Type AnimalArrayType = typeof(Animal[]);
var ctor = AnimalArrayType.GetConstructor(new[] { typeof(int) });
object[] parameters = { 3 };
var animals = (Animal[])ctor.Invoke(parameters);