var ctor = typeof(T).GetConstructor(new[]{ typeof(int), typeof(string) }); ctor.Invoke(instance, new Object[]{ 7, "Bill" });
You are looking for .GetConstructor
.
More details
Given the following object:
public class Foo { public Int32 a; public String b; public DateTime c; public Double d = 5318008; public Foo(Int32 a, String b) { this.a = a; this.b = b; } }
Calling ctor in the standard way leads to the following:
var foo = new Foo(42, "Hello, world!") { new DateTime(2014, 11, 26) }; // foo { // a=42, // b="Hello, world!", // c=11/27/2014 12:00:00 AM // d = 5318008 // }
Now let's change d:
foo.d = 319009; // foo { // a=42, // b="Hello, world!", // c=11/27/2014 12:00:00 AM // d=319009 // }
Call ctor again:
typeof(Foo) .GetConstructor(new[]{ typeof(Int32), typeof(String) }). .Invoke(foo, new Object[]{ 84, "World, Hello!" });
Note that c
remains unchanged. This is due to the fact that a and b are defined in ctor and, although not obvious, is equal to d (properties assigned at the object level are actually assigned when ctor is called).