Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling an extension method on a "null" reference (i.e. event with no subscribers) evil?

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?

like image 786
Judah Gabriel Himango Avatar asked Oct 29 '08 19:10

Judah Gabriel Himango


People also ask

Can you call extension method on null?

As extension methods are in reality static methods of another class, they work even if the reference is null .

Should extension methods check for 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.


1 Answers

Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null?

like image 117
Dan Goldstein Avatar answered Sep 21 '22 18:09

Dan Goldstein