Wednesday, 8 October 2008

Getting 'Out' Parameters to work in reflected objects C#

I've used reflection a lot in the last year but always had a bit of a problem trying to get parameters which are by reference back out correctly.

eg. i have a method call like this

public GetFoo(out string someData) {}

To specify that we have out parameter we need to use the ParameterModifier class

ParameterModifier[] arrPmods = new ParameterModifier[1];
aMods[0] = new ParameterModifier(1);
aMods[0][0] = true; // out

Not sure why we need to set a second index to true here but it works. Its to do with the fact that its late binding!!

You then need to set up a type array to specify what you are passing in so for this example it would be

Type[] aTypes[] = new Type[1];
aTypes.SetValue(Type.GetType("System.String&"), 0)

Now you can get the method information by using

MethodInfo miGetFoo = object.GetType().GetMethod("GetFoo", aTypes, aMods);

Where object has a method called GetFoo
Now all we need to do is create an array of objects but set the ParameterModifiers

miGetFoo.Invoke(object, aObj)

Get the string value

someData= (string)aObj[0]