Difference between private EventHandler and private EventHandler?

Basically what the name says. What is the difference between the two (I am currently using the first)

private EventHandler _progressEvent; 

and

 private event EventHandler _progressEvent; 

I have a method

 void Download(string url, EventHandler progressEvent) { doDownload(url) this._progressEvent = progressEvent; } 

The doDownload method will call

 _progressEvent(this, new EventArgs()); 

So far, everything is working fine. But I feel like I'm doing something terrible.

+6
source share
2 answers

The first defines the delegate, the second defines the event. The two are related to each other, but they are usually used very differently.

In general, if you use EventHandler or EventHandler<T> , this assumes that you are using an event. The caller (to process progress) usually subscribes to the event (does not pass in the delegate), and you can raise this event if you have subscribers.

If you want to use a more functional approach and pass the delegate, I would choose a more suitable delegate to use. In this case, you really do not provide any information in EventArgs , so perhaps using System.Action would be more appropriate.

Thus, an event-based approach seems to be more appropriate here, from a little code. For more information on using events, see Events in the C # Programming Guide.

Your code, using events, most likely will look something like this:

 // This might make more sense as a delegate with progress information - ie: percent done? public event EventHandler ProgressChanged; public void Download(string url) { // ... No delegate here... 

When you call your progress, you should write:

 var handler = this.ProgressChanged; if (handler != null) handler(this, EventArgs.Empty); 

A user of this type would write this as:

 yourClass.ProgressChanged += myHandler; yourClass.Download(url); 
+8
source

I do not think there is a difference between the two.

The event keyword is an access modifier, for example private internal and protected. It is used to restrict access to multicast delegates.

From everything visible to least visible, we have

 public EventHandler _progressEvent; //can be assigned to from outside the class (using = and multicast using +=) //can be invoked from outside the class public event EventHandler _progressEvent; //can be bound to from outside the class (using +=) //can be invoked from inside the class private EventHandler _progressEvent; //can be bound from inside the class (using = or +=) //can be invoked inside the class private event EventHandler _progressEvent; //Same as private. given event restricts the use of the delegate from outside // the class - i don't see how private is different to private event 
+1
source

All Articles