views:

60

answers:

2

i have the following senario:

class Addition{
 public Addition(int a){ a=5; }
 public static int add(int a,int b) {return a+b; }
}

i am calling add in another class by:

string s="add";
typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22

i need a way similar to the above reflection statement to create a new object of type Addition using Addition(int a)

so i have string s= "Addition" i want to create a new object using reflection.

is this possible?

+5  A: 

Yes, you can use Activator.CreateInstance

Ben Voigt
+6  A: 

I don't think GetMethod will do it, no - but GetConstructor will.

using System;
using System.Reflection;

class Addition
{
    public Addition(int a)
    {
        Console.WriteLine("Constructor called, a={0}", a);
    }
}

class Test
{
    static void Main()
    {
        Type type = typeof(Addition);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
        object instance = ctor.Invoke(new object[] { 10 });
    }
}

EDIT: Yes, Activator.CreateInstance will work too. Use GetConstructor if you want to have more control over things, find out the parameter names etc. Activator.CreateInstance is great if you just want to call the constructor though.

Jon Skeet
Yes, but then you have to implement all the overload resolution rules to pick the right constructor. Whereas the runtime will do it for you if you call http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx
Ben Voigt
So `GetConstructor` is preferred if you want to cache a delegate (performance enhancement when calling the same constructor many times), but for one-off use `Activator` would be easier.
Ben Voigt
@Ben: It definitely depends on your requirements, yes.
Jon Skeet