Giezi
Giezi

Reputation: 140

How to add abstract class with generic as argument of delegate in c#

I have an abstract class called StatesHandler with a generic type T. In this class, I have a delegate which is called from whithin the class:

public abstract class StatesHandler<T>
{
    public event Action<StatesHandler<T>> OnStatesChanged;

    private void Function(){
        OnStatesChanged(this);
    }
}

I then have an implementation of this abstract class, where State is an enum:

public class MyStatesHandler : StatesHandler<State>{}

In a third class, I add a listener to this delegate:

public class MyThirdClass
{
    private MyStatesHandler myStatesHandler;

    private void AddListener()
    {
        myStatesHandler.OnStatesChanged += StateChanged;
    }

    private void StateChanged(StatesHandler<State> statesHandler)
    {
    }
}

My question is why does the function added to the listener need to be of signature StatesHandler<State> and not simply MyStatesHandler?

Shouldn't both work?

Upvotes: 1

Views: 161

Answers (1)

Jasper Kent
Jasper Kent

Reputation: 3676

OnStatesChangedtakes as a parameter a StatesHandler<T> or anything derived from StatesHandler<T>.

Suppose therefore we also had

public class SomeOtherHandler : StatesHandler<State>{}

It would be possible to invoke OnStatesChanged passing an object of this class as a parameter, since it is derived from StatesHandler<T>. However, this could not be passed to

private void StateChanged(MyStatesHandler statesHandler)
{
}

since there is no inheritance relationship between MyStatesHandler and SomeOtherHandler.

Thus the event handler must take a base class parameter.

Upvotes: 2

Related Questions