Skip to content

Instantly share code, notes, and snippets.

@5cover
Last active June 10, 2023 13:29
Show Gist options
  • Save 5cover/4fd72e86b7f4eea226f732acc2baef0c to your computer and use it in GitHub Desktop.
Save 5cover/4fd72e86b7f4eea226f732acc2baef0c to your computer and use it in GitHub Desktop.
Type-safe event handler pattern. This pattern reduces the likelihood of an unhandled ``InvalidCastException`` since the ``sender`` argument of event handlers doesn't need to be casted. It also discourages the usage of closures to retrieve the sender with its original type.
/// <typeparam name="TSender">The type of the source of the event.</typeparam>
/// <typeparam name="TEventArgs">The type of event data generated by the event.</typeparam>
/// <remarks>Type-safe variation from <see cref="EventHandler{TEventArgs}"/>.</remarks>
/// <inheritdoc cref="EventHandler{TEventArgs}"/>
[Serializable]
[SuppressMessage("Naming", "CA1711", Justification = "Type-safe event handler pattern")]
public delegate void TypeEventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e);
/// <typeparam name="TSender">The type of the source of the event.</typeparam>
/// <remarks>Type-safe variation from <see cref="EventHandler"/>.</remarks>
/// <inheritdoc cref="EventHandler"/>
[Serializable]
[SuppressMessage("Naming", "CA1711", Justification = "Type-safe event handler pattern")]
public delegate void TypeEventHandler<TSender>(TSender sender, EventArgs e);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment