E-slacker
E-slacker
CC#
Created by E-slacker on 7/9/2023 in #help
❔ How to return a generic interface whose only parameter is determined on runtime?
So, I've got this code, it doesn't compile but it clarifies what I want to do:
private static IProblem<T>? GetProblem<T>(int day, T type)
{
try
{
var instance = Activator.CreateInstance(Problems[day]);
return (IProblem<T>?)instance;
}
catch (Exception e)
{
Console.Error.WriteLine(e);
return null;
}
}
private static IProblem<T>? GetProblem<T>(int day, T type)
{
try
{
var instance = Activator.CreateInstance(Problems[day]);
return (IProblem<T>?)instance;
}
catch (Exception e)
{
Console.Error.WriteLine(e);
return null;
}
}
The variable instance is of type object, I want it to be of IProblem<T> where T is a generic parameter of an interface that Problems[day] implements. I've been butting my head with this code for quite a while, but I can't find something that works. How could I accomplish this with generics? Or do I have to go dynamic?
26 replies