Using C # reflex to invoke a constructor

I have the following script:

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

I call add to another class:

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

I need a way similar to the reflection expression described above to create a new object of type Addition using Addition(int a)

So, I have the line s= "Addition" , I want to create a new object using reflection.

Is it possible?

+71
source share
2 answers

I don't think GetMethod will do this, 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 more control over things, find out parameter names, etc. Activator.CreateInstance great if you just want to call the constructor.

+128
source

Yes, you can use Activator.CreateInstance

+39
source

All Articles