Evil or not evil?
public static void Raise(this EventHandler handler, object sender, EventArgs args) { if (handler != null) { handler(sender, args); } } // Usage: MyButtonClicked.Raise(this, EventArgs.Empty); // This works too! Evil? EventHandler handler = null; handler.Raise(this, EVentArgs.Empty);
Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).
Evil or not?
As extension methods are in reality static methods of another class, they work even if the reference is null .
No its not. Because there are Nullable types as well. Null check extension method should be able to check null values of Nullable types. But our extension method is only restricted to class types where as Nullable types are in fact value types which can have null values.
Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With