Galin Iliev's blog

Software Architecture & Development

Call MethodInfo.Invoke with an out parameter

Here is a trick inspired by Visual C# Forums and C# MVP Mattias Sjögren. In this code snippet int.TryParse() method is called using reflection and get result from out parameter.

int parNum = 0;
string parText = "99";
object[] methodParms = new object[] { parText, parNum };

MethodInfo methInfo = parNum.GetType().GetMethod("TryParse", new Type[] { typeof(string), typeof(int).MakeByRefType() });
methInfo.Invoke(null, methodParms);
parNum = (int)methodParms[1];
Console.WriteLine("Parsed number:{0}", parNum);

Comments (1) -

  • Maciej Paszta

    8/6/2008 10:20:16 AM | Reply

    I just found your post - it's very interesting however what about generic methods that have parameters passed as ref or out? Your trick doesn't seem to work.