Here's how you could create a new variable using only type information, using dynamic , you can call any method that you know exists for all types. I would suggest (assuming these types are your own classes) that you implement the baseclass interface or something for them, if possible, this simplifies your pretty much ...
new List<Type> { typeof(string), typeof(int) }.ForEach(x => { dynamic processor = Activator.CreateInstance(x); processor.ToString(); processor.CallAnyMethodHere(); processor.Process(); });
Edited Code - Add a Clear Example
using System; using System.Collections.Generic; using System.Reflection; using System.Text; public class mainClass { public static void Main(string[] args) { new List<Type> { typeof(StringBuilder), typeof(Int64) }.ForEach(x => { dynamic instance = Activator.CreateInstance(x); DoSomething(instance); }); Console.ReadKey(); } public static void DoSomething(StringBuilder stringBuilder) { Console.WriteLine("StringBuilder overload"); } public static void DoSomething(Int64 int64) { Console.WriteLine("Int64 overload"); } }
Edit 2 - calling only the general method
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Linq; public class mainClass { public static void Main(string[] args) { new List<Type> { typeof(StringBuilder), typeof(Int64) }.ForEach(x => { var methodInfoArray = typeof(mainClass).GetMethods(); var methodInfo = methodInfoArray.First(mi => mi.Name == "DoSomething" && mi.IsGenericMethodDefinition); var genericMethod = methodInfo.MakeGenericMethod(new Type[] { x }); var blah = genericMethod.Invoke(null, new object[] { "Hello" }) as MethodInfo; }); Console.ReadKey(); } public static void DoSomething<T>(string variable) { Console.WriteLine("DoSomething<T> " + typeof(T) + " overload - " + variable); } public static void DoSomething(string variable) { Console.WriteLine("DoSomething - " + variable); } }
source share