title: C# - How to map an object to a generic class suited to that object type?
body: <p>(I really tried to come up with a better title, feel free to edit)</p>
  
  <p>Suppose I have a generic event handler interface and implementations:</p>
  
  <pre><code>public interface IEventHandler&lt;T&gt;
  {
      void HandleEvent(T t);
  }
  
  public class SlowButAccurateEventHandler&lt;T&gt; : IEventHandler&lt;T&gt;
  {
      // To emphasize that the implementation depends on T
      private void SomeHelperClass&lt;T&gt; helperClass;
  
      public void HandleEvent(T t) { ... }
  }
  
  public class FastEventHandler&lt;T&gt; : IEventHandler&lt;T&gt;
  {
      // To emphasize that the implementation depends on T
      private void SomeHelperClass&lt;T&gt; helperClass;
  
      public void HandleEvent(T t) { ... }
  } 
  </code></pre>
  
  <p>and another class which I'd like to hold instances of EventHandlers, but cannot have generic methods since it's a WCF service:</p>
  
  <pre><code>public class MyService : MyContract
  {
      // Pseudo (doesn't compile)
      private Dictionary&lt;Type, IEventHandler&lt;T&gt;&gt; eventHandlers;
  
      public MyService()
      {
          // More pseudo...
          eventHandlers = new Dictionary&lt;Type, IEventHandler&lt;T&gt;&gt;()
          {  
              { typeof(string), new SlowButAccurateEventHandler&lt;string&gt;() },
              { typeof(int), new FastEventHandler&lt;int&gt;() },
          };    
      }
      public void RouteToEventHandler(object userEvent)
      {
         var handler = eventHandlers[typeof(userEvent))];
         handler.HandleEvent(userEvent); // I realize that userEvent needs to be converted here
      }
  }
  </code></pre>
  
  <p>So basically, I have some service (<code>MyService</code>) that I'd like to hold <code>IEventHandlers</code> and dispatch the correct handler when some event arrives.
  To do that, I'd like to keep a dictionary that holds a mapping between the CLR type and the suitable IEventHandler. Is that possible?</p>