4

I have an out parameter. Is it possible to transfer it as reflection? Can you give me some examples how to do that?

r.r
  • 7,023
  • 28
  • 87
  • 129

1 Answers1

13

I'm not sure what this has to do with VS extensibility, but it's certainly possible to invoke a method with an out parameter by reflection and find out the out parameter's value afterwards:

using System;
using System.Reflection;

class Test
{
    static void Main()
    {
        MethodInfo method = typeof(int).GetMethod
            ("TryParse", new Type[] { typeof(string),
                                      typeof(int).MakeByRefType() });

        // Second value here will be ignored, but make sure it's the right type
        object[] args = new object[] { "10", 0 };

        object result = method.Invoke(null, args);
        Console.WriteLine("Result: {0}", result);
        Console.WriteLine("args[1]: {0}", args[1]);
    }
}

Note how you need to keep a reference to the array used to pass arguments to the method - that's how you get the out parameter value afterwards. The same is true for ref.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But what if I don't know the type of the 2nd argument? This is my question here: http://stackoverflow.com/questions/33338843/dynamically-declare-a-type-for-a-method-out-parameter – alpinescrambler Oct 26 '15 at 06:00