Calling a private .NET method with ref or out parameters using reflection

| | Comments (0) | TrackBacks (0)

I needed this yesterday and was amazed at how many forums and blogs I needed to visit before I found the answer. So I decided to blog about it myself so that I wouldn't forget about where to find the answer again.

If you have a class like this and need to call "PrivateMethod"

public class PrivateMethodClass {
  private int PrivateMethod(int arg1, ref int arg2, out int arg3) {
    arg2 = arg2 + 10;
    arg3 = 999;
    return arg1;
  }
}

This is the code you need to call it

PrivateMethodClass target = new PrivateMethodClass();
MethodInfo methodInfo = typeof(PrivateMethodClass).GetMethod(
  "PrivateMethod",
  BindingFlags.NonPublic | BindingFlags.Instance,
  null,
  new[] {
    typeof(int), 
    typeof(int).MakeByRefType(), 
    typeof(int).MakeByRefType()
  },
  null);
object[] parameters = new object[3];
parameters[0] = 1;
parameters[1] = 2;
parameters[2] = 3;
int result = (int)methodInfo.Invoke(target, parameters);
Console.WriteLine("parameter[0]: " + parameters[0]);
Console.WriteLine("parameter[1]: " + parameters[1]);
Console.WriteLine("parameter[2]: " + parameters[2]);
Console.WriteLine("result: " + result);

There are two things that are different from a typical reflection call. The first is the call to "MakeByRefType" which as the name suggests makes a reference type from a type. This is required for a "ref" or a "out" parameter. The second is the creation of the parameters array before invoking the method.

Leave a comment

0 TrackBacks

Listed below are links to blogs that reference this entry: Calling a private .NET method with ref or out parameters using reflection.

TrackBack URL for this entry: http://www.nearinfinity.com/mt/mt-tb.cgi/618