Unable to cast/match types when using generics in interfaces, why?

Viewed 1654

In IMyMessage.cs

public interface IMyMessage
{
}

In IMyMessageReceiver.cs

public interface IMyMessageReceiver<T> where T: IMyMessage
{
    void HandleMessage(T message);
    void Subscribe();
}

In MyMessagePublisher.cs

public static class MyMessagePublisher
{
    private static Dictionary<Type, List<IMyMessageReceiver<IMyMessage>>> _subscribers;

    static MyMessagePublisher
    {
         _subscribers = new Dictionary<Type, List<IMyMessageReceiver<IMyMessage>>>();
    }

    public static function Subscribe<T>(IMyMessageReceiver<T> receiver) where T: IMyMessage
    {
        Type messageType = typeof (T);
        List<IMyMessageReceiver<IMyMessage>> listeners;

        if(!_subscribers.TryGetValue(messageType, out listeners))
        {
             // no list found, so create it
             List<IMyMessageReceiver<T>> newListeners = new List<IMyMessageReceiver<T>>();
             // ERROR HERE: Can't convert List<IMyMessageReceiver<T>> to List<IMyMessageReceiver<IMyMessage>>
             _subscribers.add(messageType, newListeners);

        }

        //  I would then find the right list and add the receiver it to it but haven't got this far
    }
}

So my hope was to use a bunch of 'IMyMessages' and 'IMyMessageReceivers' to pass messages around. I did a hard coded approach earlier but got sick of 100 different publish/subscrive function names so I figured I'd wrap it all nicely in generics.

My problem is that I can't get the code to work when using generics. Even though I specify the Type T will be of IMyMessage, I cannot use T anywhere where IMyMessage is expected. Maybe I'm just used to base/extended classes as it would work fine there. I've tried various approaches from casting, to being really generic, yet I always run in to the same issue.

4 Answers
Related