I have the following code:
public class MyClass
{
public void MyMethod()
{
Action<Child> aFoo = a => a.Foo();
}
}
interface Parent1
{
void Foo();
}
interface Parent2
{
void Foo();
}
interface Child : Parent1, Parent2
{
}
However, the compiler tells me that I have an ambiguous call on aFoo
.
I tried to do Action<Child> aFoo = (A a) => a.Foo();
but it tells me that I cannot convert lambda expression to delegate type System.Action<Child>
How do I resolve the error of ambiguity?
Action<T>
is not covariant in its type parameterT
, it is contravariant. That meansAction<object>
can be converted toAction<string>
, but not the other way around.Generally put,
Action<T>
is a subtype of (read: can be assigned to)Action<U>
, only ifU
is a subtype ofT
.In your case,
Child
is a subclass ofParent
, which meansAction<Parent>
is a subclass ofAction<Child>
, allowing you to do this:But not:
That being said, try casting the lambda parameter instead:
By casting the value of
a
inside the body of the lambda:Your attempted solution did not work because it did something else entirely: it tried to fit a lambda expression taking a
Parent1
into a delegate taking aChild
. This is not possible, even though it is possible to fit a delegate taking aParent1
into a delegate taking aChild
:This latter usage is viable because
Action<T>
is contravariant on the type T.