I’m trying to add a more derived type as value to a dictionary<…, base> but i get the following error:
Cannot convert from HandleIntegrationEvent to HandleIntegrationEvent
Example
using System.Threading.Tasks;
using System.Collections.Generic;
public interface IBaseEvent
{
string Name { get; }
}
public class UserCreatedEvent: IBaseEvent
{
public string Name { get; } = "UserCreatedEvent";
}
public delegate Task HandleIntegrationEvent<in TR>(TR @event) where TR: IBaseEvent;
public class IntegrationBus
{
private readonly IDictionary<string, HandleIntegrationEvent<IBaseEvent>> _listeners = new Dictionary<string, HandleIntegrationEvent<IBaseEvent>>();
public void RegisterEventListener<TR>(string @event, HandleIntegrationEvent<TR> listener) where TR: IBaseEvent
{
// ERROR: cannot convert from HandleIntegrationEvent<TR> to HandleIntegrationEvent<IBaseEvent>
_listeners.Add(@event, listener);
}
}
I just can’t understand it and have been trying to understand the problem for some time now.
As I understand it, the generic constraint should ensure that an instance has implemented the IBaseEvent interface.
I just have a mental block in the meantime