Using C# reflection to call a constructor
Solution 1:
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.
Solution 2:
Yes, you can use Activator.CreateInstance