mo.notono.us

Friday, June 04, 2004

Reflection and ref

Using reflection, how do you determine if a method parameter is passed explicitly by reference using the ref keyword? E.g.
public Foo(int foo, ref string fooBar, out string barFoo)
{
	//...
}
The ParameterInfo class has an IsOut property which nicely informs you that the barFoo parameter is an out parameter, but IsOut if false for fooBar. There is no IsRef property, and IsRetval doesn't do the trick either. The only way I found to solve this problem was to look at the parameter type name. I stumbled on the following in the help for the ParameterBuilder class:
	// Note that we are passing the first parameter, fundsPool, by reference. Therefore,
    // we need to inform the MethodBuilder to expect a ref, by declaring the first
    // parameter's type to be System.Double& (a reference to a double).
So - the solution is: If a parameter's type name ends with an &, but it is not an out, then it must be a ref. Excerpt from a method in my latest CodeSmith template (more on it later):
...
		typeName = pi.ParameterType.Name;
		if (pi.IsOut)
			pars.Append("out ");
		else if (typeName.EndsWith("&"))
			pars.Append("ref ");
...

Labels: ,

0 Comments:

Post a Comment

<< Home