+ All Categories
Home > Documents > 7.Delegates and Events

7.Delegates and Events

Date post: 04-Jun-2018
Category:
Upload: naveen-kumar
View: 217 times
Download: 0 times
Share this document with a friend

of 48

Transcript
  • 8/13/2019 7.Delegates and Events

    1/48

    1

    Delegates and Events

    Chapter - 7

  • 8/13/2019 7.Delegates and Events

    2/48

    2

    Chapter Objectives

    .NET Delegate Types  – Basic Concepts

    How to build a C# Delegate  – Example

    Multicasting with Delegates Asynchronous Delegates

    Events  – Basic Concepts

    Listening to incoming Events

    Examples on Events

  • 8/13/2019 7.Delegates and Events

    3/48

    3

    .NET Delegate Types - Basic Concepts

    Delegates, Interfaces and Events allow you to provide callback

    functionality. Each type has its own specific usage characteristicsthat make it better suited to particular situations.

     A delegate in C# is similar to a function pointer  in C or C++.Function pointers simply represent memory address & they donot include „type-safe‟ info. 

    Solution - C# implements Delegates, it implements the call backtechnique in a much safer & more object oriented manner.

    Delegate is an object that points to another method in theapplication

     All these happen at run time and not at compile time

    Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure

     A delegate declaration defines a type that encapsulates

    name of the method

    a set of arguments

    a return type

  • 8/13/2019 7.Delegates and Events

    4/48

    4

    Defining a Delegate in C#

    Dictionary meaning – a person acting for anotherperson

    In C# - a method acting for another method

     A delegate in C# is a class type object & is used toinvoke a method that has been encapsulated into it atthe time of its creation (at run time).

    Delegates involve 4 steps-

    Delegate declaration - defines using System.Delegate 

    as a base class. Delegate method definition – any function (defined in

    a class) whose signature matches the delegatesignature exactly

  • 8/13/2019 7.Delegates and Events

    5/48

    5

    Defining a Delegate … 

    Delegate Instantiation – holds reference to delegate

    methods

    Delegate invocation – an instance is used to invoke

    the methods

     An interesting and useful property of a delegate is that

    it does not know or care about the class of the object

    that it references

    it can be used to hold reference to a method of anyclass

    all that matters is that the method's argument types

    and return type match the delegate's

  • 8/13/2019 7.Delegates and Events

    6/48

    6

    Delegate Declaration

    Syntax:Modifier delegate return-type delegate-name(parameters);

    Here, parameters – identifies the signature

    of the delegate

    Eg: delegate void SimpleDelegate();

    delegate int MathOperation (int x, int y);

    public delegate int ComareItems

    (object o1 , object o2);

  • 8/13/2019 7.Delegates and Events

    7/48

    7

    Declaration…. 

    Since delegate is a class type, it can be

    defined in

    1. Inside a class 2. outside all classes3. As the top level object in a namespace

    Delegate types are implicitly sealed

  • 8/13/2019 7.Delegates and Events

    8/48

    8

    Delegate Methods

    The methods whose references are encapsulated into

    a delegate instance are known as delegate methods or

    clallback entities.

    The signature & return type of delegate methods must

    exactly match the signature & return type of the

    delegate

    Eg: delegate void Delegate();

    Can encapsulate references to the following methods:Public void F1()

    { CW (“F1”); }

    Static public F2()

    { CW (“F2”);  }

  • 8/13/2019 7.Delegates and Events

    9/48

    9

    Delegate Methods… 

    Eg2: delegate double MathOp(double x, double y);

    Can refer any of the following methods:

    public static double multiply(double a double b)

    { return(a*b); }

    public double divide(double a double b)

    { return(a/b); }

    Don‟t care whether the method is a static or an

    instance method

  • 8/13/2019 7.Delegates and Events

    10/48

    10

    Delegate Instantiation

    General form

    new delegate-type(expression)

    Here, delegate-type – name of the delegate declared

    earlier whose object should be created

    expression – method name or a value of a delegate_type

    - If it is method name its signature & return type must be

    same as those of a delegate-type

    - Matching method can be static or instance method

    - If it is instance method, we need to specify the

    instance as well as name of the method

    - If it is static method, then specify only class name andmethod name

  • 8/13/2019 7.Delegates and Events

    11/48

    11

    Delegate Instantiation… 

    The method & object to which a delegate refers are determinedwhen delegate is instantiated & then delegate remain constant for

    the entire lifetime of the delegate

    Therefore once delegate created can‟t be change 

    Can‟t create delegate that refer constructor, indexer, or user -

    defined operator

    Eg1: delegate int ProductDelegate(int x, int y);

    class Delegate

    { static float Product(float a, float b) // sign not match

    { return(a*b); }static int Product (int a, int b) // Sign match

    { return (a*b); }

    // delegate instantiation

    ProductDelegate P=new ProductDelegate(Product);

    }

  • 8/13/2019 7.Delegates and Events

    12/48

    12

    Delegate Instantiation… 

    Eg12 delegate void DisplayDelegate();

    class A

    { Public void DisplayA()

    { CW(“Display A”);  }

    }

    class B

    { static public void DisplayB()

    { CW(“Display B”):  }

    }

    …… 

    //delegate instance

     A a = new A();

    DisplayDelegate d1=new DisplayDelegate(a.DisplayA);

    …. 

    DisplayDelegate d2 = new DisplayDelegate(B.DisplayB);

    …… 

  • 8/13/2019 7.Delegates and Events

    13/48

    13

    Delegate Invocation

    General form

    delegate-object(parameterlist)

    Here, parameter list – is optional, provides value

    Eg1: delegate1(x,y); // void delegate

    Returns void, so it cannot be used as a operand of any

    operator

    Eg2: double result = delegate2( 2.56, 45.7);

    Returns a value, so, it can be used as an operand for

    operator.

  • 8/13/2019 7.Delegates and Events

    14/48

    14

    // Program to illustrate creating & implemting a delegate

    using system;

    Delegate int ArithOp( int x, int y);

    Class MathOperation

    { public static int Add(int a, int b){ return (a+b); }

    public static int Sub(int a, int b)

    { return (a-b); }

    }

    Class Delegate_Test

    { public static void Main()

    { ArithOp Operation1 = new ArithOp(MathOperation.Add);

     ArithOp Operation2 = new ArithOp(MathOperation.Sub);

    // invoking delogatesint result1 = Operaion1( 200, 100);

    int result2=Operation2(200,100);

    CW(“Result1 =“ + result1); 

    CW(“Result2=“ +result2); 

    } }

  • 8/13/2019 7.Delegates and Events

    15/48

    15

    Delegates vs. Interfaces

    Delegates and interfaces are similar in thatthey enable the separation of specificationand implementation

    Delegate specifies the signature of amethod, and authors can write methodsthat are compatible with the delegate

    specification. Same is true even in thecase of an interface

    when should you use delegate/interface?

  • 8/13/2019 7.Delegates and Events

    16/48

    16

    Use Delegates when… 

     A single method is being called

     A class may want to have multiple implementations ofthe method specification

    It is desirable to allow using a static method to

    implement the specification  An event-like design pattern is desired

    The caller has no need to know or obtain the object thatthe method is defined on

    The provider of the implementation wants to "hand out"the implementation of the specification to only a fewselect components

    Easy composition is desired

  • 8/13/2019 7.Delegates and Events

    17/48

    17

    Use Interfaces when… 

    The specification defines a set of related

    methods that will be called

     A class typically implements thespecification only once

    The caller of the interface wants to cast to

    or from the interface type to obtain otherinterfaces or classes

  • 8/13/2019 7.Delegates and Events

    18/48

    18

    Delegate in C#

    To declare a delegate, use the keyword delegate

    public delegate void ProcessBookDelegate(Book book);

    C# automatically creates a new sealed class with threemethods:

    sealed class ProcessBookDelegate : system.MulticastDelegate 

    {

    public ProcessBookDelegate (object target, uint functionAddress);public void Invoke (Book book);

    public IAsyncResult BeginInvoke (Book book);

    public void EndInvoke (IAsyncResult result);

    }

  • 8/13/2019 7.Delegates and Events

    19/48

    19

    System.MulticastDelegate

     A multicast delegate is one that can have more than oneelement in its invocation list. This means, a multicastdelegate can point to multiple methods

    When a multicast delegate is invoked, the delegates inthe invocation linked list are called synchronously in theorder in which they appear

    Method - returns the name of the static method

    Target - gets the class instance on which the current

    delegate invokes the instance method

    Combine()  – adds a method to the list

    GetInvocationList()  – returns an array ofSystem.Delegate types

    Remove()  – removes a delegate from the list

  • 8/13/2019 7.Delegates and Events

    20/48

    20

    Example 1 – Simple: Outline

     AnyMethodTakingAString(string s) delegaterepresents an object that maintains a referenceto some method that has a string type parameterand returns void

    When you want to call the method thro' thedelegate, pass the name of the method to thedelegates constructor

     AnyMethodTakingAString del;

    del = new AnyMethodTakingAString(PlainPrint);del("BIT");

    Now PlainPrint() method will be invoked via thedelegate

  • 8/13/2019 7.Delegates and Events

    21/48

    21

    Example 1 - Simpleclass DelegateApp

    {

    // This is the method that will be called by the delegate.

    public static void PlainPrint(string msg)

    { Console.WriteLine("Msg is: {0}", msg); }

    public static void UpperCasePrint(string msg){ Console.WriteLine("Msg is: {0}", msg.ToUpper()); }

    public static void XXXXYYYYZZZZ888777aaa(string msg)

    { Console.WriteLine("Msg is: {0}", msg); }

    // Bad target! Why?

    public void BadTargetForDelegate(int x, AppDomain y){ // Stuff. }

    // Define a delegate.

    public delegate void AnyMethodTakingAString(string s);

  • 8/13/2019 7.Delegates and Events

    22/48

    22

    Main()public static void Main()

    {

    Console.WriteLine("***** A very simple delegate example *****\n");

    // Make the delegate.

     AnyMethodTakingAString del;

    del = new AnyMethodTakingAString(PlainPrint);

    del("Hello there...");

    Console.WriteLine("->I just called: {0}\n", del.Method);// Reassign and invoke delegate.

    del = new AnyMethodTakingAString(UpperCasePrint);

    del("Hello there...");

    Console.WriteLine("->I just called: {0}\n", del.Method);

    // Reassign and invoke delegate.del = new AnyMethodTakingAString(XXXXYYYYZZZZ888777aaa);

    del("Hello there...");

    Console.WriteLine("->I just called: {0}\n", del.Method);

    }

    }

  • 8/13/2019 7.Delegates and Events

    23/48

    23

    Example - 2 (Sorting)

    DelegateTesta – int array

    bool AscSort(e1, e2)

    bool DescSort(e1, e2)

    DelegateBSort.bubbleSort(a, new DelegateBSort.Comp(AscSort))

    DelegateBSort.bubbleSort(a, new DelegateBSort.Comp(DescSort))

    DelegateBSort

    delegate bool Comp(e1, e2)static void bubbleSort(a, Comp c)

  • 8/13/2019 7.Delegates and Events

    24/48

    24

    Sorting… public class DelegateBSort

    {public delegate bool Comp(int e1, int e2);public static void Swap(ref int x, ref int y)

    {

    int t;

    t = x; x = y; y = t;

    }

    public static void bubbleSort(int[ ] a, Comp c)

    {

    for(int i = 0; i < a.Length - 1; i++)

    for(int j = 0; j < a.Length - 1 - i; j++)

    {

    if (c(a[ j ], a[ j+1 ]))

    Swap(ref a[ j ], ref a[ j+1 ]);

    }

    }

    }

  • 8/13/2019 7.Delegates and Events

    25/48

    25

    public class DelegateTest

    {

    private int[ ] a = new int[4] {10, 40, 20, 30};

    // method to be called for ascending order

    public bool AscSort(int e1, int e2)

    { return e1 > e2; }// method to be called for descending order

    public bool DescSort(int e1, int e2)

    { return e1 < e2; }

    public void DispAscArr( )

    {

    // Delegate the sorting to ascending orderDelegateBSort.bubbleSort(a, new DelegateBSort.Comp(AscSort));

    for (int i = 0; i < a.Length ; i++)

    Console.WriteLine(a[i]);

    }

    public void DispDescArr( )

    {// Delegate the sorting to descending order

    DelegateBSort.bubbleSort(a, new DelegateBSort.Comp(DescSort));

    for (int i = 0; i < a.Length ; i++)

    Console.WriteLine(a[i]);

    }

    }

  • 8/13/2019 7.Delegates and Events

    26/48

    26

    Main()

    public static void Main(string[ ] args)

    {

    DelegateTest obj = new DelegateTest ( );

    Console.WriteLine("Ascending Array: ");

    obj.DispAscArr ( );

    Console.WriteLine("Descending Array: ");

    obj.DispDescArr ( );

    }

  • 8/13/2019 7.Delegates and Events

    27/48

    27

    Example - 3 (Abstract Model)Main( )

    g.ProcessCars(new Car.CarDelegate(WashCar) )

    static void WashCar(Car c)

    static void RotateTires(Car c)

    Garage

    theCars - ArrayList

    void ProcessCars(Car.CarDelegate proc) 

    Car

    isDirty

    shouldRotate

    delegate void CarDelegate (Car c) 

  • 8/13/2019 7.Delegates and Events

    28/48

  • 8/13/2019 7.Delegates and Events

    29/48

    29

    Garage Class This delegate encapsulates a function pointer to some

    method taking a Car and returning void.public class Garage

    {

    // We have some cars.

     ArrayList theCars = new ArrayList();

    public Garage()

    {

    theCars.Add(new Car("Viper", 100, 0, true, false));

    theCars.Add(new Car("Fred", 100, 0, false, false));

    theCars.Add(new Car("BillyBob", 100, 0, false, true));theCars.Add(new Car("Bart", 100, 0, true, true));

    theCars.Add(new Car("Stan", 100, 0, false, true));

    }

  • 8/13/2019 7.Delegates and Events

    30/48

    30

    Garage Class… 

    This method takes a CarDelegate as aparameter. Therefore, 'proc' is nothing morethan a function pointer...

    public void ProcessCars(Car.CarDelegate proc){

    ………. 

    foreach(Car c in theCars)

    proc(c);

    }

  • 8/13/2019 7.Delegates and Events

    31/48

    31

    CarApp Classpublic class ServiceDept

    {

    // A target for the delegate.

    public static void WashCar(Car c)

    {

    if(c.Dirty)

    Console.WriteLine("Cleaning a car");

    else

    Console.WriteLine("This car is already clean...");

    }

    // Another target for the delgate.

    public static void RotateTires(Car c)

    {

    if(c.Rotate)

    Console.WriteLine("Tires have been rotated");

    else

    Console.WriteLine("Don't need to be rotated...");

    }

    }

  • 8/13/2019 7.Delegates and Events

    32/48

    32

    Main()

    One way of using the delegates (because WashCarand RotateTires are static methods)

    Garage g = new Garage();

    // Wash all dirty cars.

    g.ProcessCars(new Car.CarDelegate(WashCar));// Rotate the tires.

    g.ProcessCars(new Car.CarDelegate(RotateTires));

    If they are non-static, then use the following syntax:

    ServiceDept sd = new ServiceDept();

    g.ProcessCars(new Car.CarDelegate(sd.WashCar));

    g.ProcessCars(new Car.CarDelegate(sd.RotateTires));

  • 8/13/2019 7.Delegates and Events

    33/48

    33

    Multicasting

    Multicast delegate can call any number of

    Methods

    For multicasting you can use + operator which is

    overloaded

    Garage g = new Garage();

    // Create two new delegates

    Car.CarDelegate w = new Car.CarDelegate (WashCar));

    Car.CarDelegate r = new Car.CarDelegate (RotateTires));

    g.ProcessCars(w + r);

  • 8/13/2019 7.Delegates and Events

    34/48

    34

    Events  An event is an action which you can respond to, or

    "handle," in code Events can be generated by a user action, such as

    clicking the mouse or pressing a key; by program code;or by the system (e.g. Mouse Click event)

    Events are widely used in GUI-based programming

    (VB6.0) Buttons, TextBox, ComboBox, etc report back to the

    enclosing Form (Listener).

    How is it useful in C# ? Take for example the Car class.When some thing goes abnormal (excess speed) an

    exception is raised and the program may halt!  A better solution is to inform the object for some action.

    Delegates are classes commonly used within the .NETFramework to build event-handling mechanisms.

  • 8/13/2019 7.Delegates and Events

    35/48

    35

    Establishing Events

    Events, however, need not be used only for graphicalinterfaces

    Events provide a generally useful way for objects tosignal state changes that may be useful to clients of thatobject

    Events are an important building block for creatingclasses that can be reused in a large number of differentprograms

    Declaration of events is a two step process:

    define a delegate when an event occurs, the methods held by the delegate will be

    executed

    Define the events using C# 'event ' keyword

  • 8/13/2019 7.Delegates and Events

    36/48

    36

    Basic Event Model

  • 8/13/2019 7.Delegates and Events

    37/48

    37

    Abstract Model

    Declaring an Event (Car Class)public delegate void EngineHandler(string msg);

    public static event EngineHandler Exploded;

    public static event EngineHandler AboutToBlow;

    Invoking / Firing an Event 

    if(Exploded != null)

    Exploded("Sorry, this car is dead...");

    Hooking up / Subscribing to an Event

    Car.Exploded += new Car.EngineHandler(sink.OnBlowUp);

    Car.AboutToBlow += new Car.EngineHandler(sink.OnAboutToBlow);

  • 8/13/2019 7.Delegates and Events

    38/48

    38

    Car Example – Declaring an Event

    public class Car

    {

    // The delegate for our events.

    public delegate void EngineHandler(string msg);

    // This car can send these events.

    public static event EngineHandler Exploded;

    public static event EngineHandler AboutToBlow;

    ……… 

    }

    bli id S dU (i t d lt )

  • 8/13/2019 7.Delegates and Events

    39/48

    39

    public void SpeedUp(int delta)

    {

    // If the car is dead, send event.

    if(carIsDead)

    {

    if(Exploded != null)

    Exploded("Sorry, this car is dead...");

    }

    else

    {

    currSpeed += delta;// Almost dead?

    if(10 == maxSpeed - currSpeed)

    if(AboutToBlow != null)

     AboutToBlow("Careful, approaching terminal speed!");

    // Still OK!

    if(currSpeed >= maxSpeed)carIsDead = true;

    else

    Console.WriteLine("--> CurrSpeed = {0}", currSpeed);

    }

    }

  • 8/13/2019 7.Delegates and Events

    40/48

    40

    Listening to Car Events

    public class CarEventSink

    {

    // OnBlowUp event sink A.

    public void OnBlowUp(string s)

    {

    Console.WriteLine("Message from car: {0}", s);

    }

    public void OnAboutToBlow(string s)

    {

    Console.WriteLine("Message from car: {0}", s);}

    }

  • 8/13/2019 7.Delegates and Events

    41/48

    41

    Main()public class CarApp

    {public static int Main(string[] args)

    {

    // Make a car as usual.

    Car c1 = new Car("SlugBug", 100, 10);

    // Make sink object.CarEventSink sink = new CarEventSink();

    // Hook into events.

    Console.WriteLine("***** Hooking into car events *****");

    Car.Exploded += new Car.EngineHandler(sink.OnBlowUp);

    Car.AboutToBlow += new

    Car.EngineHandler(sink.OnAboutToBlow);

    // Detach from events.

    Car.Exploded -= new Car.EngineHandler(sink.OnBlowUp);

    }

  • 8/13/2019 7.Delegates and Events

    42/48

    42

    Bank Example

     An event will be raised when an overdraft occurs(you may use a callback delegate also)

     Account – Class

    OverDraftEventHandler – Delegate

    OnOverdraftHandler – Event Clients can subscribe using the following methods:

     AddOnOverdraft

    RemoveOnOverdraft

    EventArgs - is a base class for event argumentclasses. In case if your event has to passadditional information to its subscribers, asubclass is needed

  • 8/13/2019 7.Delegates and Events

    43/48

  • 8/13/2019 7.Delegates and Events

    44/48

    44

    public int Balance

    {

    get { return balance; }

    }

    public void Deposit(int aDeposit){

    if (aDeposit < 0) throw new ArgumentOutOfRangeException();

    balance = balance + aDeposit;

    }

    public bool Withdrawl(int aDebit)

    {if(aDebit < 0)

    throw new ArgumentOutOfRangeException();

    if(aDebit < balance)

    {

    balance = balance - aDebit;

    return true;

    }

    OverdraftEventArgs args = new OverdraftEventArgs(balance, aDebit);

    OnOverdraft(args);

    return false;

    }

  • 8/13/2019 7.Delegates and Events

    45/48

    45

    public void AddOnOverdraft(OverdraftEventHandler handler)

    {

    OnOverdraftHandler += handler;

    }

    public void RemoveOnOverdraft

    (OverdraftEventHandler handler)

    {

    OnOverdraftHandler -= handler;

    }

    protected void OnOverdraft(OverdraftEventArgs e)

    {

    if(OnOverdraftHandler != null)OnOverdraftHandler(this, e); // firing the event

    }

    }

  • 8/13/2019 7.Delegates and Events

    46/48

    46

    Eventpublic class OverdraftEventArgs : EventArgs

    {

    protected int balance;

    protected int withdrawl;

    public OverdraftEventArgs(int bal, int wd)

    {

    balance = bal;

    withdrawl = wd;}

    public int Balance

    {

    get { return balance; }

    }public int Withdrawl

    {

    get { return withdrawl; }

    }

    }

  • 8/13/2019 7.Delegates and Events

    47/48

    47

    Main

    public class Client

    {public static void OnOverdraft(object sender, OverdraftEventArgs e)

    {

    Console.WriteLine("An overdraft occurred");

    Console.WriteLine("The account balance is = {0}",e.Balance);

    Console.WriteLine("The with drawl was = {0}",e.Withdrawl);}

    public static void Main(string[] args)

    {

     Account myAccount = new Account(100);

     Account.OverdraftEventHandler h = null;

    h = new Account.OverdraftEventHandler(OnOverdraft);

    myAccount.AddOnOverdraft(h);

    }

    }

  • 8/13/2019 7.Delegates and Events

    48/48

    48

    End of Chapter 7


Recommended