Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between delegates and events?

Delegate does the same job of function pointers. It can be viewed as the function pointers of the managed world. It simply represents the address of a function to call, along with a specific object whose method is to be called.

Many times I read the term Delegate along with the termEvent but I can not see the relationship between them. Is the Event a specific type of delegates?

like image 287
Aan Avatar asked Feb 28 '12 17:02

Aan


People also ask

How delegates and events are related?

A delegate is a way of telling C# which method to call when an event is triggered. For example, if you click a Button on a form, the program would call a specific method. It is this pointer that is a delegate. Delegates are good, as you can notify several methods that an event has occurred, if you wish so.

What is the difference between delegate and events?

Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.

What does it mean to be a delegate at an event?

countable noun. A delegate is a person who is chosen to vote or make decisions on behalf of a group of other people, especially at a conference or a meeting.

Why do we need events when we have delegates?

Yes, Events! This is a simplified explanation on why we use events even though we can already use delegates: To provide encapsulation and not exposing business logic. To prevent Team Client from clearing all assign methods to delegates (You cannot do that for events):


1 Answers

Short answer: see my article on the topic. Longer answer:

Events are a pattern on top of delegates. They're an implementation of the publisher/subscriber pattern (aka observer pattern), using delegates as the means of representing a subscription.

Whenever you see something like:

public event EventHandler Foo;

you should instead think of two methods:

public void AddFooHandler(EventHandler handler) { ... }
public void RemoveFooHandler(EventHandler handler) { ... }

All that a client from the outside can do is subscribe and unsubscribe. In particular, the client cannot raise the event themselves (without a separate method being provided for that purpose) nor can they "replace" or remove other subscriptions.

like image 74
Jon Skeet Avatar answered Oct 11 '22 14:10

Jon Skeet