Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active August 29, 2015 14:07
Show Gist options
  • Save Porges/228a07d4df6b8000d9fb to your computer and use it in GitHub Desktop.
Save Porges/228a07d4df6b8000d9fb to your computer and use it in GitHub Desktop.
Simple safe event raising
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