HelterSkelter HelterSkelter - 1 year ago 91
C# Question

GetConstructors doesn't find the declared constructor

I'm experimenting with

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

using System;
using System.Reflection;

class Animal
public Animal (string s)

class Test
public static void Main()
Type AnimalArrayType = typeof(Animal).MakeArrayType();

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

Answer Source

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);

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

Type AnimalArrayType = typeof(Animal[]);

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download