This is how you would create a new variable using only type information, by using dynamic
you are able to call any method which you know exists for all of the types. I would suggest (assuming these types are your own classes) you implement an interface baseclass or something for these if possible, it simplify your quite a lot...
new List<Type> { typeof(string), typeof(int) }.ForEach(x =>
{
dynamic processor = Activator.CreateInstance(x);
processor.ToString();
processor.CallAnyMethodHere();
processor.Process();
});
Edited code - Adding 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 - Only call generic 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);
}
}