5 ms·
It annoyed me that in C#, you have to check whether someone is subscribed to an event before raising it. An Extension Method: public static bool CheckedRai
by frou_dh 15y ago
It annoyed me that in C#, you have to check whether someone is subscribed to an event before raising it. An Extension Method:
public static bool CheckedRaise<T>(this EventHandler<T> eh, object sender, T e)
where T : EventArgs
{
bool check = eh != null;
if (check)
eh(sender, e);
return check;
}
- noblethrasher 15y agoYou probably already know this but another trick is just to assign an "empty" lambda to the event. public event SomeDelegate MyEvent = (sender, e) => {}; Or better yet public event SomeDelegate MyEvent = delegate {};
- frou_dh 15y agoYep, but with either of those, it can still be set back to null :)
- noblethrasher 15y agoTrue. I don't use events much but when I do I use the following pattern: private SomeDelegate _myEvent = delegate {}; public event SomeDelegate MyEvent { add { _myEvent += value; } remove { _myEvent -= value; } }
- frou_dh 15y agoIf I'm not mistaken, that has the same semantics as the standard one line event definition, i.e.: public event EventHandler MyEvent; // Inside the class, MyEvent is bound to a multicast delegate. // Outside the class, MyEvent is bound to an auto-generated add/remove mechanism. // So MyEvent can only be set to null or invoked from inside the class.
- noblethrasher 15y agoHmmm, you're right. That's two (C# related) things I learned today.