Search code examples
c#visual-studioparametersvsxextensibility

how to pass/transfer out parameter as reflection? - visual studio extensibility c#


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


Solution

  • 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.