How to delegate correct Action<Interface>?

.net, c#, compiler-errors, delegates, interface

Solution

You can't do what you're trying to do - you're expecting covariance, but `Action<T>` is contravariant on its only type-parameter.

You can't do a method-group conversion from `evtCheck` to `Action<IFace>` because `evtCheck` needs a more specific type (`IntEvent`) as its argument than the more general `IFace` type that an `Action<IFace>` instance expects. If such a conversion were allowed, what would you expect to happen if the delegate were executed with an argument that implements `IFace` but is not an `IntEvent`?

I think you should have another look at your design because it looks like there's a flaw there, but if you want, you can create a lambda to force a cast of the argument to the desired type and accept the possibility of an `InvalidCastException`:

setAction(iFace => evtCheck((IntEvent)iface));

More likely, you might want to make `evtCheck` accept a more general type or `setAction` to accept a more specific delegate.

Problem

I'm a beginner with C# and can't find any answer for this : Im trying to delegate Actions with some interface parameter , but push through functions with objects that extend this interface (or class) ``` // some class extending interface public class IntEvent : IFace{} public class MoveEvent : IFace{} // function i like to use to verify Action static void setAction(Action<IFace> evt) { // evt ... } // function to delegate as Action static void evtCheck(IntEvent evt) { // some func } static void evtMove(MoveEvent evt) { // some func } // class { // call method inside class and delegate this function : setAction(evtCheck); setAction(evtMove); ``` I'm receiving an error that "`evtCheck(IntEvent)` cannot be converted to `Action<IFace>`" , even if `IntEvent` extends the `IFace` interface . How should I solve this ? Maybe I have to use Func or Delegate ?

Original source