Events and Delegates

Events are used to decouple the Caller from the Methods Calls.

Events are used to replace Method Calls.


Events encapsulate the Method Calls, along with Sender, Method Name and Data Passed to Method.


Events are used to decouple the important Domain Event and its Reaction.


Events are used to decouple the important occurrence in domain to the reaction code that should have to be executed against it.


Events are used to decouple Domain Action from Domain Reaction.

We decouple because the Domain Reaction/Business Logic could change over the time. For example, different Discount Rates, Different Promotions, Different Formals for Price Calculations.



Event is the Collection of EH-Methods. Delegates are used to define Events and tell about the signature of all EH-Methods.



Event has 6 steps related to them


1. Defining the Event Argument Class that encapsulate the Method Call. As told, Event is the O.O Representation of a Method Call. Methods take arguments, so the Event also takes argument. This class encapsulates the Domain Objects needed by Event Handlers to process the reactive Business Logic. It encapsulate the Data that we want to provide to the Subscribers to process the reactive Business Logic or Domain Logic. What is needed by the Event Handler is encapsulated inside the Event Arguments Class.


2. Defining the Delegates in the Publisher as public member. This defines the Method Signature of Event Handlers of all Subscribers those will listen to this event. All Event Handlers of an Event will have same signature and definition of this Method Signature is defined inside the publisher as Delegate. DELEGATE is used to tell EVENT about the METHOD SIGNATURE of all EVENT HANDLERS. Delegates are used in the definition of Events. Event is the Collection of EH-Methods. Delegates are used to define Events and tell about the signature of all EH-Methods.


3. Defining the Event instance variable inside the Publisher. This definition include the Delegate Definition inside it. This Event Variable is used to store the List of Event Handlers of interested Subscribers. Event is the Array of Method/Event Handlers Pointers such that Event Handlers have same signature. It holds the reference of all Methods/EH of different Subscribers. This is Array of Subscriber's Methods not the Array of Subscribers. So, Delegates are used in the definition of Events. Event is the Collection of EH-Methods. Delegates are used to define Events and tell about the signature of all EH-Methods.


4. Raising an Event inside the Publisher. This is a magic Method Call. Raising an event means, we calling the EH Methods of all Subscribers when something interesting happens inside Publisher. One Method Call results in Several Method Call. 5 subscribers 5 EH method calls. This is like iterating over the list of subscribers and calling their Event-Handlers. If there are Subscribers then raise the Event if not then Event is not Raised.


5. Definition of the Event Handlers. It is defined inside the Subscribers. Event Handler could be inside the Container or inside any Object inside the Container. So Subscriber could be container or it could be separate Object Living inside the Container.


6. Binding the Publisher's Events and Subscriber's EH Methods.  This is done either inside the Subscriber or in Container. Either we bind Event to Container's EH-Method or it could be bind to any other Container's Object's EH-Methods.

==============================

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.

An event is a notification by the .NET framework that an action has occurred. Each event contains information about the specific event, e.g., a mouse click would say which mouse button was clicked where on the form.

Delegates[edit]

Delegates form the basis of event handling in C#. They are a construct for abstracting and creating objects that reference methods and can be used to call those methods. A delegate declaration specifies a particular method signature. References to one or more methods can be added to a delegate instance. The delegate instance can then be "called", which effectively calls all the methods that have been added to the delegate instance. A simple example:

using System;
delegate void Procedure();

class DelegateDemo
{
    public static void Method1()
    {
        Console.WriteLine("Method 1");
    }

    public static void Method2()
    {
        Console.WriteLine("Method 2");
    }

    public void Method3()
    {
        Console.WriteLine("Method 3");
    }

    static void Main()
    {
        Procedure someProcs = null;

        someProcs += new Procedure(DelegateDemo.Method1);
        someProcs += new Procedure(Method2);  // Example with omitted class name

        DelegateDemo demo = new DelegateDemo();

        someProcs += new Procedure(demo.Method3);
        someProcs();
    }
}



Methods that have been added to a delegate instance can be removed with the -= operator:
someProcs -= new Procedure(DelegateDemo.Method1);
In C# 2.0, adding or removing a method reference to a delegate instance can be shortened as follows:
someProcs += DelegateDemo.Method1;
someProcs -= DelegateDemo.Method1;
Invoking a delegate instance that presently contains no method references results in a NullReferenceException.
Note that, if a delegate declaration specifies a return type and multiple methods are added to a delegate instance, an invocation of the delegate instance returns the return value of the last method referenced. The return values of the other methods cannot be retrieved (unless explicitly stored somewhere in addition to being returned).

Events[edit]

An event is a special kind of delegate that facilitates event-driven programming. Events are class members that cannot be called outside of the class regardless of its access specifier. So, for example, an event declared to be public would allow other classes the use of += and -= on the event, but firing the event (i.e. invoking the delegate) is only allowed in the class containing the event. A simple example:
delegate void ButtonClickedHandler();
class Button
{
    public event ButtonClickedHandler ButtonClicked;
    ButtonClicked += ()=>{Console.WriteLine("click simulation !")};    
    public void SimulateClick()
    {
        if (ButtonClicked != null)
        {
            ButtonClicked();
        }
    }
    ...
}
A method in another class can then subscribe to the event by adding one of its methods to the event delegate:
Button b = new Button();
b.ButtonClicked += ButtonClickHandler();
Even though the event is declared public, it cannot be directly fired anywhere except in the class containing it.

BASIS FOR COMPARISONDELEGATESEVENTS
BasicA delegate holds the reference of a method.The event is an over-layered abstraction provided to the delegates.
Syntaxdelegate return_type delegate_name(parameter_list);event event_delegate event_name;
KeywordA delegate is declared using a keyword "delegate."An Event is declared using a keyword "event".
DeclarationA delegate is declared outside any class.An event is declared inside a class.
InvokeTo invoke a method it has to be referred to the delegate.To invoke a method it has to be assigned to the event.
Covariance and ContravarianceThey provide flexibility to the delegates.No such concept.
Event AccessorNo such concept.Manages the list of the event handlers.
DependencyDelegates are independent of events.The event can not be created without delegates.







No comments:

Post a Comment