(Using .NET 4.0) Ok, so I have
private Dictionary<int, Action<IMyInterface, IMyInterface>> handler {get; set;}
public void Foo<T, U>(Action<T, U> myAction)
where T : IMyInterface
where U : IMyInterface
{
// | This line Fails
// V
Action<IMyInterface, IMyInterface> anotherAction = myAction;
handler.Add(someInt, anotherAction);
}
I'm trying to store the delegate in a generic collection, so I can pull it back out later to invoke it. How do I properly cast it?
Welp... looks like me and my friend found a bit of a work around.
With a simple lambda wrap, we accomplished what we needed.
I don't think there is a type safe way of doing what you're trying to accomplish. Using the example in your updated question:
Assuming IMyInterface and MyImplementation are defined as follows:
We could find ourselves in the following situation:
It's for this reason that the Action generic is contravariant (you can use less specific types, but not more specific types).
The generic parameters to the Action delegate are type-contravariant; they are not type covariant. As a result, you can pass in a less specific type, but not a more specific type.
So this compiles:
But this doesn't:
Since
T and U : IMyInterface
, your code is analogous to the first example.The intellisense explains it rather clearly: (here's a bigger version)