title: Event Signature in .NET -- Using a Strong Typed 'Sender'?
body: <p>I fully realize that what I am proposing does not follow the .NET guidelines, and, therefore, is probably a poor idea for this reason alone. However, I would like to consider this from two possible perspectives:</p>
  
  <p>(1) Should I consider using this for my own development work, which is 100% for internal purposes.</p>
  
  <p>(2) Is this a concept that the framework designers could consider changing or updating?</p>
  
  <p>I am thinking about using an event signature that utilizes a strong typed 'sender', instead of typing it as 'object', which is the current .NET design pattern. That is, instead of using a standard event signature that looks like this:</p>
  
  <pre><code>class Publisher
  {
      public event EventHandler&lt;PublisherEventArgs&gt; SomeEvent;
  }
  </code></pre>
  
  <p>I am considering using an event signature that utilizes a strong-typed 'sender' parameter, as follows:</p>
  
  <p>First, define a "StrongTypedEventHandler":</p>
  
  <pre><code>[SerializableAttribute]
  public delegate void StrongTypedEventHandler&lt;TSender, TEventArgs&gt;(
      TSender sender,
      TEventArgs e
  )
  where TEventArgs : EventArgs;
  </code></pre>
  
  <p>This is not all that different from an Action&lt;TSender, TEventArgs&gt;, but by making use of the <code>StrongTypedEventHandler</code>, we enforce that the TEventArgs derives from <code>System.EventArgs</code>.</p>
  
  <p>Next, as an example, we can make use of the StrongTypedEventHandler in a publishing class as follows:</p>
  
  <pre><code>class Publisher
  {
      public event StrongTypedEventHandler&lt;Publisher, PublisherEventArgs&gt; SomeEvent;
  
      protected void OnSomeEvent()
      {
          if (SomeEvent != null)
          {
              SomeEvent(this, new PublisherEventArgs(...));
          }
      }
  }
  </code></pre>
  
  <p>The above arrangement would enable subscribers to utilize a strong-typed event handler that did not require casting:</p>
  
  <pre><code>class Subscriber
  {
      void SomeEventHandler(Publisher sender, PublisherEventArgs e)
      {           
          if (sender.Name == "John Smith")
          {
              // ...
          }
      }
  }
  </code></pre>
  
  <p>I do fully realize that this breaks with the standard .NET event-handling pattern; however, keep in mind that contravariance would enable a subscriber to use a traditional event handling signature if desired:</p>
  
  <pre><code>class Subscriber
  {
      void SomeEventHandler(object sender, PublisherEventArgs e)
      {           
          if (((Publisher)sender).Name == "John Smith")
          {
              // ...
          }
      }
  }
  </code></pre>
  
  <p>That is, if an event handler needed to subscribe to events from disparate (or perhaps unknown) object types, the handler could type the 'sender' parameter as 'object' in order to handle the full breadth of potential sender objects.</p>
  
  <p>Other than breaking convention (which is something that I do not take lightly, believe me) I cannot think of any downsides to this.</p>
  
  <p>There may be some CLS compliance issues here. This does run in Visual Basic .NET 2008 100% fine (I've tested), but I believe that the older versions of Visual Basic .NET through 2005 do not have delegate covariance and contravariance. <em>[Edit: I have since tested this, and it is confirmed: VB.NET 2005 and below cannot handle this, but VB.NET 2008 is 100% fine. See "Edit #2", below.]</em> There may be other .NET languages that also have a problem with this, I can't be sure.</p>
  
  <p>But I do not see myself developing for any language other than C# or Visual Basic .NET, and I do not mind restricting it to C# and VB.NET for .NET Framework 3.0 and above. (I could not imagine going back to 2.0 at this point, to be honest.)</p>
  
  <p>Can anyone else think of a problem with this? Or does this simply break with convention so much that it makes people's stomachs turn?</p>
  
  <p>Here are some related links that I've found:</p>
  
  <p>(1) <a href="http://msdn.microsoft.com/en-us/library/ms229011.aspx" rel="noreferrer">Event Design Guidelines [MSDN 3.5]</a></p>
  
  <p>(2) <a href="https://stackoverflow.com/questions/809609/c-simple-event-raising-using-sender-vs-custom-eventargs">C# simple Event Raising - using “sender” vs. custom EventArgs [StackOverflow 2009]</a></p>
  
  <p>(3) <a href="https://stackoverflow.com/questions/247241/event-signature-pattern-in-net">Event signature pattern in .net [StackOverflow 2008]</a></p>
  
  <p>I am interested in anyone's and everyone's opinion on this...</p>
  
  <p>Thanks in advance,</p>
  
  <p>Mike</p>
  
  <p><strong>Edit #1:</strong> This is in response to <a href="https://stackoverflow.com/questions/1046016/event-signature-in-net-using-a-strong-typed-sender/1046104#1046104"> Tommy Carlier's post </a>:</p>
  
  <p>Here's a full working example that shows that both strong-typed event handlers and the current standard event handlers that use a 'object sender' parameter can co-exist with this approach. You can copy-paste in the code and give it a run:</p>
  
  <pre><code>namespace csScrap.GenericEventHandling
  {
      class PublisherEventArgs : EventArgs
      {
          // ...
      }
  
      [SerializableAttribute]
      public delegate void StrongTypedEventHandler&lt;TSender, TEventArgs&gt;(
          TSender sender,
          TEventArgs e
      )
      where TEventArgs : EventArgs;
  
      class Publisher
      {
          public event StrongTypedEventHandler&lt;Publisher, PublisherEventArgs&gt; SomeEvent;
  
          public void OnSomeEvent()
          {
              if (SomeEvent != null)
              {
                  SomeEvent(this, new PublisherEventArgs());
              }
          }
      }
  
      class StrongTypedSubscriber
      {
          public void SomeEventHandler(Publisher sender, PublisherEventArgs e)
          {
              MessageBox.Show("StrongTypedSubscriber.SomeEventHandler called.");
          }
      }
  
      class TraditionalSubscriber
      {
          public void SomeEventHandler(object sender, PublisherEventArgs e)
          {
              MessageBox.Show("TraditionalSubscriber.SomeEventHandler called.");
          }
      }
  
      class Tester
      {
          public static void Main()
          {
              Publisher publisher = new Publisher();
  
              StrongTypedSubscriber strongTypedSubscriber = new StrongTypedSubscriber();
              TraditionalSubscriber traditionalSubscriber = new TraditionalSubscriber();
  
              publisher.SomeEvent += strongTypedSubscriber.SomeEventHandler;
              publisher.SomeEvent += traditionalSubscriber.SomeEventHandler;
  
              publisher.OnSomeEvent();
          }
      }
  }
  </code></pre>
  
  <p><strong>Edit #2:</strong> This is in response to <a href="https://stackoverflow.com/questions/1046016/event-signature-in-net-using-a-strong-typed-sender/1046041#1046041">Andrew Hare's statement</a> regarding covariance and contravariance and how it applies here. Delegates in the C# language have had covariance and contravariance for so long that it just feels "intrinsic", but it's not. It might even be something that is enabled in the CLR, I don't know, but Visual Basic .NET did not get covariance and contravariance capability for its delegates until the .NET Framework 3.0 (VB.NET 2008). And as a result, Visual Basic.NET for .NET 2.0 and below would not be able to utilize this approach.</p>
  
  <p>For example, the above example can be translated into VB.NET as follows:</p>
  
  <pre><code>Namespace GenericEventHandling
      Class PublisherEventArgs
          Inherits EventArgs
          ' ...
          ' ...
      End Class
  
      &lt;SerializableAttribute()&gt; _
      Public Delegate Sub StrongTypedEventHandler(Of TSender, TEventArgs As EventArgs) _
          (ByVal sender As TSender, ByVal e As TEventArgs)
  
      Class Publisher
          Public Event SomeEvent As StrongTypedEventHandler(Of Publisher, PublisherEventArgs)
  
          Public Sub OnSomeEvent()
              RaiseEvent SomeEvent(Me, New PublisherEventArgs)
          End Sub
      End Class
  
      Class StrongTypedSubscriber
          Public Sub SomeEventHandler(ByVal sender As Publisher, ByVal e As PublisherEventArgs)
              MessageBox.Show("StrongTypedSubscriber.SomeEventHandler called.")
          End Sub
      End Class
  
      Class TraditionalSubscriber
          Public Sub SomeEventHandler(ByVal sender As Object, ByVal e As PublisherEventArgs)
              MessageBox.Show("TraditionalSubscriber.SomeEventHandler called.")
          End Sub
      End Class
  
      Class Tester
          Public Shared Sub Main()
              Dim publisher As Publisher = New Publisher
  
              Dim strongTypedSubscriber As StrongTypedSubscriber = New StrongTypedSubscriber
              Dim traditionalSubscriber As TraditionalSubscriber = New TraditionalSubscriber
  
              AddHandler publisher.SomeEvent, AddressOf strongTypedSubscriber.SomeEventHandler
              AddHandler publisher.SomeEvent, AddressOf traditionalSubscriber.SomeEventHandler
  
              publisher.OnSomeEvent()
          End Sub
      End Class
  End Namespace
  </code></pre>
  
  <p>VB.NET 2008 can run it 100% fine. But I've now tested it on VB.NET 2005, just to be sure, and it does not compile, stating:</p>
  
  <blockquote>
    <p>Method 'Public Sub
    SomeEventHandler(sender As Object, e
    As
    vbGenericEventHandling.GenericEventHandling.PublisherEventArgs)'
    does not have the same signature as
    delegate 'Delegate Sub
    StrongTypedEventHandler(Of TSender,
    TEventArgs As System.EventArgs)(sender
    As Publisher, e As
    PublisherEventArgs)'</p>
  </blockquote>
  
  <p>Basically, delegates are invariant in VB.NET versions 2005 and below. I actually thought of this idea a couple of years ago, but VB.NET's inability to deal with this bothered me... But I've now moved solidly to C#, and VB.NET can now handle it, so, well, hence this post.</p>
  
  <p><strong>Edit: Update #3</strong></p>
  
  <p>Ok, I have been using this quite successfully for a while now. It really is a nice system. I decided to name my "StrongTypedEventHandler" as "GenericEventHandler", defined as follows:</p>
  
  <pre><code>[SerializableAttribute]
  public delegate void GenericEventHandler&lt;TSender, TEventArgs&gt;(
      TSender sender,
      TEventArgs e
  )
  where TEventArgs : EventArgs;
  </code></pre>
  
  <p>Other than this renaming, I implemented it exactly as discussed above.</p>
  
  <p>It does trip over FxCop rule CA1009, which states:</p>
  
  <blockquote>
    <p>"By convention, .NET events have two
    parameters that  specify the event
    sender and event data. Event handler 
    signatures should follow this form:
    void MyEventHandler( object sender,
    EventArgs e). The 'sender' parameter 
    is always of type System.Object, even
    if it is possible  to employ a more
    specific type. The 'e' parameter is 
    always of type System.EventArgs.
    Events that do not  provide event data
    should use the System.EventHandler 
    delegate type. Event handlers return
    void so that they  can send each event
    to multiple target methods. Any  value
    returned by a target would be lost
    after the  first call."</p>
  </blockquote>
  
  <p>Of course, we know all this, and are breaking the rules anyway. (All event handlers can use the standard 'object Sender' in their signature if preferred in any case -- this is a non-breaking change.)</p>
  
  <p>So the use of a <code>SuppressMessageAttribute</code> does the trick:</p>
  
  <pre><code>[SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly",
      Justification = "Using strong-typed GenericEventHandler&lt;TSender, TEventArgs&gt; event handler pattern.")]
  </code></pre>
  
  <p>I hope that this approach becomes the standard at some point in the future. It really works very nicely.</p>
  
  <p>Thanks for all your opinions guys, I really appreciate it...</p>
  
  <p>Mike</p>