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 ?
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
evtChecktoAction<IFace>becauseevtCheckneeds a more specific type (IntEvent) as its argument than the more generalIFacetype that anAction<IFace>instance expects. If such a conversion were allowed, what would you expect to happen if the delegate were executed with an argument that implementsIFacebut is not anIntEvent?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:More likely, you might want to make
evtCheckaccept a more general type orsetActionto accept a more specific delegate.