I have a dictionary that I’m using to facilitate some internal routing based on api version numbers. Essentially what happens is that I look up and operation in the dictionary and attempt to call it’s RUN method. But in order to do this, I need to be able to cast the object to it’s interface. Here’s what I mean, this is the dictionary:
public Dictionary<string, Type> Routing = new Dictionary<string, Type>();
public VersionRouter()
{
Routing.Add("1.0", typeof(OperationV1<RequestObjectV1, ResponseObjectV1>));
Routing.Add("2.0", typeof(OperationV1<RequestObjectV2, ResponseObjectV1>));
Routing.Add("3.0", typeof(OperationV1<RequestObjectV2, ResponseObjectV2>));
}
I can grab the correct type that I want to instantiate like so:
var myOperation = Routing["2.0"];
And then under normal circumstances, I’d just instantiate and cast it like this:
var myInstance = (MyInterface) Activator.CreateInstance(myOperation);
However, the interface is generic because it needs to know what the Request and Response types are:
var myInstance = (MyInterface<TRequest, TResponse>) Activator.CreateInstance(myOperation);
I don’t know how to tell it what those request and response types are at this stage. I’m assuming it can be done with reflection. I’ve found that I can get those generic parameters out through something like myOperation.GetGenericArguments() but I’m not sure how to use that to my advantage at this stage. Does anyone know how to do this?
That’s inherently impossible.
You cannot express this type at compile-time, since you don’t know the type parameters until runtime.
Therefore, you cannot cast to it, or have a variable of that type.
If possible, you should make the interface covariant, and cast it to use a base type.
Alternatively, you can make a non-generic or covariant base interface and use that instead.