laconicdev
laconicdev

Reputation: 6440

Calling a function with an out argument using Invoke

I have an ojbect with a function that takes an out argument. I want to call this function using reflection's Invoke. However, I can't find a way to specify that it's an out argument, as it is returned null.

Class Foo
{
    void Do(out string a){ a="fx call"; }
}

Foo f = new Foo();
string param = string.Empty;
f.GetType().GetMethod("Do").Invoke(f, new object[] { param });
Assert.IsTrue( ! string.IsNullOrEmpty(param));

The above call the assertion fails, since param is Empty. How can I specify that the argumetn that is being passed is "out" ?

Thanks!

Upvotes: 2

Views: 167

Answers (1)

JaredPar
JaredPar

Reputation: 754715

Reflection will update the value in the array, not the value passed into the array. Hold onto the array reference and the value will be updated inline.

string param = string.Empty;
object[] args = new object[] {param};
f.GetType().GetMethod("Do").Invoke(f, args);
param = (string)args[0];

Upvotes: 7

Related Questions