Search code examples
c#methodsreflectionvalue-typemethodinfo

How to pass a ValueType arg to a Method in C# reflection?


My question is that a method requires a long type arg and i want to execute it by reflection. However, MethodInfo needs a array of object and long is a value type, it cannot be cast to object. How to solve it?

e.g.(just a example)

class A
{
  bool IsZero(long a)
  {
    return a == 0;
  }
}

Solution

  • parameter must be specified via object[]

    A myClassAInstance = new A();
    MethodInfo mi = myClassAInstance.GetType().GetMethod("IsZero");
    long myLong = 23;
    var result = (bool)mi.Invoke(myClassAInstance, new object[]{myLong});
    

    myLong is automatically boxed.

    if you have an int, you must cast it into long

    long myInt = 11;
    var result = (bool)mi.Invoke(myClassAInstance, new object[]{(long)myInt});
    

    The number of the elements and the element types in the array must match the number and type of the parameters (signature match)