8

In a very Simple class like below,

class Program 
{

    public Program(int a, int b, int c)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
 }

and I use reflection to invoke the constructor

something like this...

   var constructorInfo = typeof(Program).GetConstructor(new[] { typeof(int), typeof(int),      typeof(int) });
        object[] lobject = new object[] { };
        int one = 1;
        int two = 2;
        int three = 3;
        lobject[0] = one;
        lobject[1] = two;
        lobject[2] = three;

        if (constructorInfo != null)
        {
            constructorInfo.Invoke(constructorInfo, lobject.ToArray);
        }

But I am getting an error saying "object does not match target type constructor info".

any help/comments greatly appreciated. thanks in advance.

1 Answer 1

19

You don't need to pass constructorInfo as a parameter, as soon as you are calling a constructor, but not an instance method of an object.

var constructorInfo = typeof(Program).GetConstructor(
                          new[] { typeof(int), typeof(int), typeof(int) });
if (constructorInfo != null)
{
    object[] lobject = new object[] { 1, 2, 3 };
    constructorInfo.Invoke(lobject);
}

For KeyValuePair<T,U>:

public Program(KeyValuePair<int, string> p)
{
    Console.WriteLine(string.Format("{0}:\t{1}", p.Key, p.Value));
}

static void Main(string[] args)
{
    var constructorInfo = typeof(Program).GetConstructor(
                             new[] { typeof(KeyValuePair<int, string>) });
    if (constructorInfo != null)
    {
        constructorInfo.Invoke(
            new object[] { 
                new KeyValuePair<int, string>(1, "value for key 1") });
    }

    Console.ReadLine();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Suppose If I have a keyvalue pair in the constructor, can then I invoke by the same method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.