title: EventHandler with a strongly typed sender in C#
body: <p>One thing that annoys me is that in a default Event, Sender is of type object and therefore almost always requires a manual cast before we can use it. Luckily since VB now also supports variance in delegates, we can update the signature of an event in such a way that the sender is strongly typed, see: <a href="https://stackoverflow.com/questions/4944633/event-parameter-sender-as-object-or-sender-as-t">Event parameter; &quot;sender as Object&quot;, or &quot;sender as T&quot;?</a> </p>
  
  <p>Unfortunatly this doesn't work for existing declared events which senders are of type object.</p>
  
  <p>Now one solution would be ofcourse to generate a fake EventHandler which internally takes care of the cast for you. I made a quick example, see:</p>
  
  <pre><code>struct EventHandler&lt;TSender, TEventArgs&gt;
      where TEventArgs: EventArgs
  {
      private readonly Action&lt;TSender, TEventArgs&gt; _delegate;
  
      public EventHandler(Action&lt;TSender, TEventArgs&gt; @delegate)
      {
          if (@delegate == null)
              throw new ArgumentNullException("@delegate");
  
          _delegate = @delegate;
      }
  
      public static implicit operator EventHandler&lt;TEventArgs&gt;(EventHandler&lt;TSender, TEventArgs&gt; eventHandler)
      {
          return new EventHandler&lt;TEventArgs&gt;(eventHandler.Execute);
      }
  
      private void Execute(object sender, EventArgs e)
      {
          TSender typedSender = (TSender)sender;
          TEventArgs typedEventArgs = (TEventArgs)e;
  
          _delegate(typedSender, typedEventArgs);
      }
  }
  </code></pre>
  
  <p>which can be used as you would expect it to be used:</p>
  
  <pre><code>class Program
  {
      event EventHandler&lt;EventArgs&gt; Test;
  
      static void Main(string[] args)
      {
          new Program().Main();
      }
  
      void Main()
      {
          Test += new EventHandler&lt;Program, EventArgs&gt;(TestEventHandler);
  
          Test(this, EventArgs.Empty);
      }
  
      void TestEventHandler(Program sender, EventArgs e)
      {
          throw new NotImplementedException();
      }
  }
  </code></pre>
  
  <p>Now if I really want to use this, there is alot of work to be done. (The struct should behave just like the original delegate). Yet i do have the feeling that there is either already a great implementation out there, or there is no implementation since there are some major drawbacks i overlooked.</p>
  
  <p>Who can answer me the above question? Any other hints?</p>