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?
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.
Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.
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.
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):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With