Difference between private EventHandler and private event EventHandler?
The first defines a delegate, the second defines an event. The two are related, but they're typically used very differently.
In general, if you're using EventHandler
or EventHandler<T>
, this would suggest that you're using an event. The caller (for handling progress) would typically subscribe to the event (not pass in a delegate), and you'd raise the event if you have subscribers.
If you want to use a more functional approach, and pass in a delegate, I would choose a more appropriate delegate to use. In this case, you're not really providing any information in the EventArgs
, so perhaps just using System.Action
would be more appropriate.
That being said, an event approach appears more appropriate here, from the little code shown. For details on using events, see Events in the C# Programming Guide.
Your code, using events, would likely look something like:
// 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'd write:
var handler = this.ProgressChanged;
if (handler != null)
handler(this, EventArgs.Empty);
The user of this would write this as:
yourClass.ProgressChanged += myHandler;
yourClass.Download(url);
For private
, there is no difference between the two, but for public
you would want to use event
.
The event keyword is an access modifier like private internal and protected. It is used for restricting access to multicast delegates. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
Going from most 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 +=), but can't be assigned (using =)
//can only 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