asked on
Set type at runtime
public object Test(int whatType)
{
dynamic ret;
if whatType = 1
{
T = blabla;
}
else
{
T = somethingelse;
}
ret = GetData<T>()
return ret;
}
Here I want to set T to a class to use it in GetData. This must be decided in runtime.
Outside of doing what Lukasz Zielinski shows, the only other way to accomplish this would be through reflection:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
object x = Test(2);
Console.WriteLine(x);
Console.ReadKey();
}
public static object Test(int whatType)
{
dynamic ret;
Func<object> func;
Type t;
if (whatType == 1)
{
t = typeof(int);
}
else
{
t = typeof(string);
}
func = GetGenericMethod(t); // Use reflection to create a delegate that represents the generic version of your method.
ret = func(); // Invoke delegate
return ret;
}
private static dynamic GetData<T>()
{
// Do something with T
if (typeof(T) == typeof(string))
{
return "Hello World!";
}
else if (typeof(T) == typeof(int))
{
return 99;
}
else
{
throw new ArgumentException("Invalid type argument.");
}
}
private static Func<object> GetGenericMethod(Type t)
{
Type program = typeof(Program);
System.Reflection.MethodInfo methodInfo = program.GetMethod(nameof(GetData), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); // Change binding flags according to how your method is devined
System.Reflection.MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(t);
Func<object> func = (Func<object>)genericMethodInfo.CreateDelegate(typeof(Func<object>));
return func;
}
}
}
@Kaufmed: :P Why would you ever want to do that nowadays though? :)
{
dynamic ret;
if (whatType == 1)
{
ret = GetData<int>();
}
else
{
ret = GetData<byte>();
}
return ret;
}