Mega Code Archive

 
Categories / C# Book / 09 Reflection
 

0628 Method Parameters

Suppose we want to dynamically call string's Substring method. Statically, this would be done as follows: using System; using System.Reflection; using System.Collections.Generic; class Program { static void Main() { Console.WriteLine("rntsoft.com".Substring(2)); } } Here's the dynamic equivalent with reflection: using System; using System.Reflection; using System.Collections.Generic; class Program { static void Main() { Type type = typeof(string); Type[] parameterTypes = { typeof(int) }; MethodInfo method = type.GetMethod("Substring", parameterTypes); object[] arguments = { 2 }; object returnValue = method.Invoke("rntsoft.com", arguments); Console.WriteLine(returnValue); } }