By casting the value of a
inside the body of the lambda:
Action<Child> aFoo = a => ((Parent1)a).Foo();
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 a Child
. This is not possible, even though it is possible to fit a delegate taking a Parent1
into a delegate taking a Child
:
Action<Child> aFoo = (Action<Parent1>)(a => a.Foo());
This latter usage is viable because Action<T>
is contravariant on the type T.