Error when casting System.Action using contravariance in C#

39 views Asked by At

I have an interface with an event with the sender as the argument.

public interface IShootAttackChild
{
    public event System.Action<IShootAttackChild> OnDestroy;
    /* and some functions */
}

I also have a class that has an event which works the same.

public class BulletController
{
    public event System.Action<BulletController> OnDestroy;
}

When i implement the interface i have to create a second event that would do the same as the first one. So to avoid that i want to use the add/remove stuff to make the interface event use the already existing class event.

public class BulletController : IShootAttackChild
{
    public event System.Action<BulletController> OnDestroy;

    event System.Action<IShootAttackChild> IShootAttackChild.OnDestroy
    {
        add
        {
            OnDestroy += value;
        }
        remove
        {
            OnDestroy -= value;
        }
    }
}

It compiles fine (these are scripts for my game so they are compiled by Unity 2022.3.4f1) but when the game tries to execute OnDestroy += value; or OnDestroy -= value; i get this error:

ArgumentException: Incompatible Delegate Types. First is System.Action`1[[BulletController, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]] second is System.Action`1[[IShootAttackChild, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]].

I don't understand why that is as the cast should be possible due to contravariance. Can anyone explain why this happens and what can i do?

This somehow works fine

event System.Action<IShootAttackChild> IShootAttackChild.OnDestroy
{
    add
    {
        OnDestroy += value.Invoke;
    }
    remove
    {
        OnDestroy -= value.Invoke;
    }
}
0

There are 0 answers