❔ 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:
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?
17 Replies
Yoiu can't use new, need to specifically use Activator class?
what is the type of Problems
I can't use new with a Assembly that I get on runtime, can I? What I want to do, basically, is to get all classes of the project that implement IProblem<> and call some of their methods
Type[] of different classes all implementing IProblem<>
what is the error you get with this block
InvalidCastException
System.InvalidCastException: Unable to cast object of type 'Problems.Day1.Day1' to type 'Utils.IProblem`1[System.Type]
oh, it compiles, just doesn't run
Oh yeah my bad
Day1 implements IProblem<int>
Day1 doesn't implement IProblem<Type>
you gave it Type for T
Oh
Given a Type object, how can i get its actual type?
to use as a generic? you can't, really
is IProblem your interface?
Yes
Should I just use dynamic?
could just get rid of the generic on IProblem, just using object instead
dynamic would also probably work? no reason to use it if you don't have to
oh well, there's absolutely no way to use generics in this case?
not if you want to return it as an actual instance of IProblem
I see, thanks a lot for your time
i didnt touch it myself, but is this what u r looking for? https://learn.microsoft.com/en-us/dotnet/api/system.type.makegenerictype?view=net-7.0
Type.MakeGenericType(Type[]) Method (System)
Substitutes the elements of an array of types for the type parameters of the current generic type definition and returns a Type object representing the resulting constructed type.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.