C#C
C#3y ago
13 replies
Altef

Generic types and inheritance

Hello,
I am trying to implement a basic event bus to have a single point for subscribing and publishing events and keeping clients anonymous from each others.
However I am having trouble defining type genericity for my event objects.

Attached file is the complete code extract.
The issue is raised at line 53 in subscribe() method when I try to add the event handler to my collection.
private void subscribe<TEvent, TEventHandler>()
    where TEvent : Event
    where TEventHandler : IEventHandler<TEvent>, new()
{
    if (!_subjects.ContainsKey(typeof(TEvent)))
    {
        _subjects.Add(typeof(TEvent), new List<IEventHandler<Event>>());
    }
    _subjects[typeof(TEvent)].Add(new TEventHandler());
}

I am getting this error :
Argument 1: cannot convert from 'TEventHandler' to 'Events.IEventHandler<Events.Event>' (CS1503)

I don't know if I should look around improving the type constraints or if my _subjects dictionary should be typed differently.

Any help would be much appreciated 🙂


----
Full code extract below :
Events.cs2.39KB
Was this page helpful?