Raise and handle events generically


/ Published in: C#
Save to your folder(s)

For a discussion of .NET events best-practices, see [Roy Osherove's blog post](http://weblogs.asp.net/rosherove/articles/DefensiveEventPublishing.aspx) and [this post](http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx). Be sure to read the comments sections for some good arguments for and against the presented methods. Also, there is a good [MSDN Magazine article on Event Accessors](http://msdn.microsoft.com/en-us/magazine/cc163533.aspx), which may be useful.

Used in "Empire." The example shows an EventArgs with a DateTime object, but it could be a string or enumeration or whatever.


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Generic EventArgs class to hold event data.
  3. /// </summary>
  4. /// <example>
  5. /// To create an event that sends a string (such as an error message):
  6. /// <code>
  7. /// public event EventHandler{EventArgs{string}} EventOccurred;
  8. /// EventOccurred.Raise(sender, "The event occurred");
  9. /// </code>
  10. /// </example>
  11. /// <see cref="http://geekswithblogs.net/HouseOfBilz/archive/2009/02/15/re-thinking-c-events.aspx"/>
  12. /// <typeparam name="T">Any data</typeparam>
  13. public class EventArgs<T> : EventArgs
  14. {
  15. public T Args { get; private set; }
  16. public EventArgs(T args)
  17. {
  18. Args = args;
  19. }
  20. public override string ToString()
  21. {
  22. return Args.ToString();
  23. }
  24. }
  25. /// <summary>
  26. /// Tell subscribers, if any, that this event has been raised.
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="handler">The generic event handler</param>
  30. /// <param name="sender">this or null, usually</param>
  31. /// <param name="args">Whatever you want sent</param>
  32. public static void Raise<T>(this EventHandler<EventArgs<T>> handler, object sender, T args)
  33. {
  34. // Copy to temp var to be thread-safe (taken from C# 3.0 Cookbook - don't know if it's true)
  35. EventHandler<EventArgs<T>> copy = handler;
  36. if (copy != null)
  37. {
  38. copy(sender, new EventArgs<T>(args));
  39. }
  40. }
  41.  
  42. class Tester
  43. {
  44. public static event EventHandler<EventArgs<DateTime>> GetTime_Rcvd;
  45.  
  46. static void Main()
  47. {
  48. GetTime_Rcvd.Raise(null, MyDateTime);
  49. }
  50. }

URL: http://geekswithblogs.net/HouseOfBilz/archive/2009/02/15/re-thinking-c-events.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.