collection of different generic types

c#, generics

Solution

I think the best approach here is to use the OfType extension method and keep your List, assuming the type of the event is known at compile time; there will still be a cast, but you will not be doing it and you will only get the entries that can actually handle that event.

Problem

Given the following interface: ``` public interface IEventHandler<in TEvent> where TEvent : IEvent { void Process(TEvent @event); } ``` What IEnumerable type can I use to store a collection of `IEventHandler<TEvent>` implementations where TEvent is different? i.e. Given the following 3 implementations: ``` public class BlahEvent1EventHandler : IEventHandler<Event1> { ... } public class WhateverEvent1EventHandler : IEventHandler<Event1> { ... } public class BlahEvent2EventHandler : IEventHandler<Event2> { ... } ``` Can I do any better than a collection of objects? ``` var handlers = new List<object> { new BlahEvent1EventHandler(), new WhateverEvent1EventHandler(), new BlahEvent2EventHandler(), }; ``` BTW, have seen some other answers advocating the use of a base type or inherited non-generic interface but cannot see how that would add a huge amount of value in this case unless I am missing something. Yes, it would let me add them all to the collection in a slightly more type safe way that using object, but would not let me iterate over them and call the strongly typed Process method without casting just as I need to do with object. ``` public interface IEventHandler { } public interface IEventHandler<in TEvent> : IEventHandler where TEvent : IEvent { void Process(TEvent @event); } ``` I still need to cast if I have `IEnumerable<IEventHandler>` or `IEnumerable<obect>` ``` foreach (var handler in _handlers.Cast<IEventHandler<TEvent>>()) { handler.Process(@event); } ``` Any thoughts on how to improve this?

Original source