OfirD
OfirD

Reputation: 10490

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

Upvotes: 1

Views: 2005

Answers (1)

recursive
recursive

Reputation: 86124

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

Upvotes: 4

Related Questions