Tuesday, May 19, 2009

Invoke with out param

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);

No comments: