Sina Karvandi
Sina Karvandi

Reputation: 1102

Get constructor(s) of an assembly with details

According to simulating the .Net assemblies I am trying to get constructor(s) of an assembly with parameters names and parameters data types. I use this code :

SampleAssembly = Assembly.LoadFrom("");

ConstructorInfo[] constructor = SampleAssembly.GetTypes()[0].GetConstructors();

foreach (ConstructorInfo items in constructor)
{
    ParameterInfo[] Params = items.GetParameters();
    foreach (ParameterInfo itema in Params)
    {
        System.Windows.Forms.MessageBox.Show(itema.ParameterType + " " + itema.Name);
    }
}

But it seems that there is nothing in itema But I implement the same scenario on the Methods and works ! (Im sure that my assembly contains more than 2 constructors with diffrent parameters) .

So any suggestion to retrieve constructor(s) of an assembly with parameter(s)?!

Edit : I use the correct path on the main code . in the : Assembly.LoadFrom("");

Thanks in advance.

Upvotes: 0

Views: 1407

Answers (2)

Balázs
Balázs

Reputation: 2929

It works for me. You have forgotten to specify the assembly path, though:

SampleAssembly = Assembly.LoadFrom("");

Should be something like:

SampleAssembly = Assembly.LoadFrom("C:\\Stuff\\YourAssembly.dll");

Edit: To respond to your comment, set a breakpoint and see what GetTypes()[0] holds. Even if you create only 1 class explicitly there might be for example anonymous classes. You should not assume that the class you want to reflect over is indeed the one and only in the assembly.

If you write a code like this:

class Program
{
  static void Main()
  {
        Type t = typeof(Program);
        ConstructorInfo[] constructor = t.GetConstructors();

        foreach (ConstructorInfo items in constructor)
        {
            ParameterInfo[] Params = items.GetParameters();

            foreach (ParameterInfo itema in Params)
              System.Windows.Forms.MessageBox.Show(itema.ParameterType + " " + itema.Name);
        }   
  }

  public Program() {}
  public Program(String s) {}
}

you will see that the code to extract the parameter types and names should and will work, so the problem is with locating the class. Try finding the class by its fully qualified name.

Upvotes: 1

msmolcic
msmolcic

Reputation: 6567

I think that your problem is that you're taking only constructors of your Type at index [0].

Check out if this works:

List<ConstructorInfo> constructors = new List<ConstructorInfo>();
Type[] types = SampleAssembly.GetTypes();
foreach (Type type in types)
{
    constructors.AddRange(type.GetConstructors());
}

foreach (ConstructorInfo items in constructors)
{
    ParameterInfo[] Params = items.GetParameters();
    foreach (ParameterInfo itema in Params)
    {
        System.Windows.Forms.MessageBox.Show(itema.ParameterType + " " + itema.Name);
    }
}

Upvotes: 2

Related Questions