What is the difference between the following code to add new events

- If I define an event with an initial empty delegate, I do not need to check for null

class MyClass { public event EventHandler<MyEventArgs> MyEvent = delegate { }; void SomeMethod() { ... MyEvent(); // No need to check for null ... } } 

- Otherwise, I need to check for null

 class MyClass { public event EventHandler<MyEventArgs> MyEvent; void SomeMethod() { ... if (MyEvent != null) // No need to check for null MyEvent(); ... } } 

What is the difference between the two? When is one better than the other?

thanks

+4
source share
3 answers

The above answer is dramatically wrong, I have to post the answer. Someone is mistaken on the Internet, still can not sleep.

It is convenient, but it does not come for free. The compiler must generate a class for the anonymous method, and the JIT compiler must generate code for it. And this code is always executed when you raise an event, regardless of whether the client has signed the event handler or not. Zero-check code is also always executed, but it requires much less code and time.

It is not a lot of code and a lot of time. Zero checking takes two machine code instructions and must be performed in a single CPU cycle. An anonymous delegate takes about an order of magnitude longer, but that's not so much on a modern machine. Personally, I'm too old to be so wasteful that the two options are my choice.

Not least because it is a standard template, everyone recognizes it.

+3
source

The first is an applicable solution, but it has a very small performance limit for invoking an additional empty delegate.

The second solution is not thread safe (if it is important to you, reasons).

You should use the following:

 var handler = MyEvent; if (handler != null ) handler(this, new MyEventArgs()); 
+2
source

At our company, we wrote an extension method that captures most events and checks to see if it is null before the call.

We have reduced this:

 var handler = MyEvent; if (handler != null) { handler(...); } 

to

 MyEvent.SafeTrigger(...); 
+1
source

Source: https://habr.com/ru/post/1303220/


All Articles