bairog bairog - 4 months ago 32
C# Question

Unable to cast object of type System.Int32 to System.Object[] when calling generic method with parameters via reflection

Les't say I have some class with two constructors (without parameters and with them):

public class Employee
private int Salary = 0;

public Employee()
Salary = 100;

public Employee(int newSalary)
Salary = newSalary;

And I have some static helper class that have generic methods to call constructors:

public static class GenericClassCreator
public static T CreateClassNoParams<T>()
where T : class, new()
return new T();

public static T CreateClassWithParams<T>(params object[] args)
where T : class
return (T)Activator.CreateInstance(typeof(T), args);

Lets assume I have Type of class that I need to construct (typeof(Employee) in this particular case) and call it's constructor with the following code:

var method1 = typeof(GenericClassCreator).GetMethod("CreateClassNoParams");
var generic1 = method1.MakeGenericMethod(typeof(Employee));

var employee1 = generic1.Invoke(null, null);

var method2 = typeof(GenericClassCreator).GetMethod("CreateClassWithParams");
var generic2 = method2.MakeGenericMethod(typeof(Employee));

var employee2 = generic2.Invoke(null, new object[] { (object)500 });

Obtaining employee1 (via constructor without parameters) is ok. But obtaining employee2 (via constructor with parameter) throws exception:

Unable to cast object of type System.Int32 to System.Object[]

Even if I change

generic.Invoke(null, new object[] { (object)500 });


generic.Invoke(null, new object[] { new object() });

exception is thrown

Unable to cast object of type System.Object to System.Object[]

So what's wrong with my code?


Your method is expecting an object[] as parameter. MethodInfo.Invoke expects an object[] containing all the parameters. This means that you need an object[] containing another object[]:

var employee2 = generic2.Invoke(null, new object[] { new object[] { 500 } });