Last active
August 29, 2015 14:07
-
-
Save Porges/228a07d4df6b8000d9fb to your computer and use it in GitHub Desktop.
Simple safe event raising
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Foo | |
{ | |
event EventHandler DoAThing; | |
void WhyYouEvenGottaDoAThing() | |
{ | |
DoAThing.Raise(this); | |
} | |
} | |
public static class EventExtensions | |
{ | |
public static void Raise(this EventHandler handler, object sender) | |
{ | |
handler.Raise(sender, EventArgs.Empty); | |
} | |
public static void Raise(this EventHandler handler, object sender, EventArgs args) | |
{ | |
if (handler != null) | |
{ | |
handler(sender, args); | |
} | |
} | |
public static void Raise<T>(this EventHandler<T> handler, object sender, T args) | |
// you will need where T : EventArgs if < .NET 4.5 | |
{ | |
if (handler != null) | |
{ | |
handler(sender, args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment