Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Main Purpose of Events in C#

I've been examining one of my c# books and I just saw a sentence about Events in C#:
 The main purpose of events is to prevent subscribers from interfering with each other.

Whatever it means, yeah actually events are working pretty much like delegates.
I've been wondering why I should use events instead of delegates.

So is there any one who can explain the bold part?

Thanks in advance.

like image 582
Tarik Avatar asked Apr 06 '10 06:04

Tarik


2 Answers

The choice wouldn't really be between a delegate and an event - they're completely different things. You could, however, expose a public property or a public field which had a delegate type. I assume that's what you really mean.

Suppose Button.Click were a public field or property instead of an event. One piece of code could then subscribe to an event, and another could then write:

// Invalid with events, valid with properties
button.Click = null;

thus wiping out the original event handler. Likewise other code would also be able to invoke the event handlers:

// Invalid with events, valid with properties
button.Click(this, EventArgs.Empty);

even though the button hadn't been clicked. This is clearly a violation of encapsulation. The only reason to expose Click to other code is to allow them to register interest in button clicks and register disinterest later - and those are exactly the abilities that events provide.

Think of events as syntactic sugar around two methods. For example, if we didn't have events then Button would probably have:

public void AddClickHandler(EventHandler handler)
public void RemoveClickHandler(EventHandler handler)

The violation of encapsulation goes away, but you lose some of the convenience - and everyone has to write their own methods like that. Events simplify this pattern, basically.

like image 61
Jon Skeet Avatar answered Oct 06 '22 23:10

Jon Skeet


An event can only be invoked by the class defining it, whereas a delegate can be invoked from whomever has access to it. This here is what I believe the bold text means.

Also, an event can be defined in an interface, whereas a delegate cannot (as you would declare the delegate as a field).

I recommend giving this link a read, as it explains it quite nicely and has a few more examples other than the above mentioned.

like image 38
Kyle Rosendo Avatar answered Oct 06 '22 23:10

Kyle Rosendo