How to pass a parameter as a reference with MethodInfo.Invoke

You need to create the argument array first, and keep a reference to it. The out parameter value will then be stored in the array. So you can use:

object[] arguments = new object[] { "test", null };
MethodInfo method = ...;
bool b = (bool) method.Invoke(null, arguments);
byte[] rawAsm = (byte[]) arguments[1];

Note how you don’t need to provide the value for the second argument, because it’s an out parameter – the value will be set by the method. If it were a ref parameter (instead of out) then the initial value would be used – but the value in the array could still be replaced by the method.

Short but complete sample:

using System;
using System.Reflection;

class Test
    static void Main()
        object[] arguments = new object[1];
        MethodInfo method = typeof(Test).GetMethod("SampleMethod");
        method.Invoke(null, arguments);
        Console.WriteLine(arguments[0]); // Prints Hello

    public static void SampleMethod(out string text)
        text = "Hello";

Leave a Comment