Delegates and Events

Difference between Delegate and events ?

    Main difference between delegate and event is in event any time you can add or remove the delegate reference. Suppose we don't want to call the method which is raised by event in some point of time we can use events.

An event is a delegate with safety constraint.
  • You can only call an event from the class that holds it.
  • You can only register/unregister to an event from outside the class (only +=/-=)
  • You cannot pass an event as parameter
  • You can only wipe clean an event from the class that holds it (eventName = null)

In some ways, you can think of a delegate type as being a bit like an interface with a single method. It specifies the signature of a method, and when you have a delegate instance, you can make a call to it as if it were a method with the same signature. Delegates provide other features, but the ability to make calls with a particular signature is the reason for the existence of the delegate concept. Delegates hold a reference to a method, and (for instance methods) a reference to the target object the method should be called on.

Events are pairs of methods, appropriately decorated in IL to tie them together and let languages know that the methods represent events.
The add and remove methods are called in C# using 
eventName += delegateInstance; and eventName -= delegateInstance; respectively.

Ref :
http://csharpindepth.com/Articles/Chapter2/Events.aspx


The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." In this model, you have publishers who will do some logic and publish an "event." Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.

1. Using EventHandler we can implement events.
2. Using delegates  we can implement custom events.

What is delegate and how it is typesafe ?

Delegate is an object having the reference to a method used for implementing the callback mechanism. Since in compile time any type mismatch will be treated as error unlike c pointers this is type safe ad won't cause any memory issues.

Multicast delegate : 

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/how-to-combine-delegates-multicast-delegates

 


No comments:

Post a Comment

Pages