/ Published in: C#
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.
Used in "Empire." The example shows an EventArgs with a DateTime object, but it could be a string or enumeration or whatever.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/// <summary> /// Generic EventArgs class to hold event data. /// </summary> /// <example> /// To create an event that sends a string (such as an error message): /// <code> /// public event EventHandler{EventArgs{string}} EventOccurred; /// EventOccurred.Raise(sender, "The event occurred"); /// </code> /// </example> /// <see cref="http://geekswithblogs.net/HouseOfBilz/archive/2009/02/15/re-thinking-c-events.aspx"/> /// <typeparam name="T">Any data</typeparam> public class EventArgs<T> : EventArgs { public T Args { get; private set; } public EventArgs(T args) { Args = args; } public override string ToString() { return Args.ToString(); } } /// <summary> /// Tell subscribers, if any, that this event has been raised. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="handler">The generic event handler</param> /// <param name="sender">this or null, usually</param> /// <param name="args">Whatever you want sent</param> public static void Raise<T>(this EventHandler<EventArgs<T>> handler, object sender, T args) { // Copy to temp var to be thread-safe (taken from C# 3.0 Cookbook - don't know if it's true) EventHandler<EventArgs<T>> copy = handler; if (copy != null) { } } class Tester { public static event EventHandler<EventArgs<DateTime>> GetTime_Rcvd; static void Main() { GetTime_Rcvd.Raise(null, MyDateTime); } }
URL: http://geekswithblogs.net/HouseOfBilz/archive/2009/02/15/re-thinking-c-events.aspx