- Home /
Action contravarience issue, throwing ArgumentException: Incompatible Delegate Types
I am attempting to define an event as a part of an interface, but have derived types implement more derived versions of that event while still allowing classes accessing the derived type through the interface to subscribe to the event. My code looks something like this:
public interface IWorkItem {
event Action<IWorkItem> WorkCompleteEvent;
}
public class Task : IWorkItem {
public event Action<Task> TaskCompleteEvent;
event Action<IWorkItem> IWorkItem.WorkCompleteEvent
{
add
{
TaskCompleteEvent += value;
}
remove
{
TaskCompleteEvent -= value;
}
}
}
public class SubscriberClass
{
void Subscribe()
{
IWorkItem myWorkItem = new Task();
myWorkItem.WorkCompleteEvent += OnWorkComplete; // This line throws the exception
}
void OnWorkComplete(IWorkItem workItem)
{
// Do Stuff
}
}
But when this code gets called , I get an exception that Action<Task> and Action<IWorkItem> are incompatible delegate types.
According to the C# documentation this should be legal with Action<T> in .NET Framework 4. Unity's API compatibility is set to .NET 4.x
Answer by Bunny83 · Sep 27, 2019 at 12:47 AM
Have you tried:
myWorkItem.WorkCompleteEvent += new Action<IWorkItem>(OnWorkComplete);
If that doesn't work, I would recommend to define your own delegate type for your IWorkItem interface:
public delegate void OnWorkCompletedEvent(IWorkItem aItem);
and also make sure you actually create an instance of your explicit delegate. See this SO question for more details
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Delegate Covariance and Contravariance using .NET 4.x Equivalent 2 Answers
Can't get touchpad to Increase sensitivity as distance between start position increases 1 Answer
Rooms are infinitely spawning, don't know what's keeping the loop from ending 1 Answer