Delegates and Events.ppt

Embed Size (px)

Citation preview

  • 8/14/2019 Delegates and Events.ppt

    1/22

    C# Delegates and Events

    C# Delegates and EventsCNS 3260

    C# .NET Software Development

  • 8/14/2019 Delegates and Events.ppt

    2/22

    C# Delegates and Events

    Delegate types

    A delegate declaration defines a new type

    Delegates are similar to function pointers Delegates are type-safe

    Delegates are object-oriented

    Delegate types are derived fromSystem.MulticastDelegate

  • 8/14/2019 Delegates and Events.ppt

    3/22

    C# Delegates and Events

    The Command Pattern

    Exposed Command Variable Command object instance

    Command executor

    Command Class

    Execute()

    Command issuer

    Command Subclass

    Execute()

    Knows when the

    event happens but

    doesnt know what to

    do about it

    Knows what to do

    when an event

    happens but doesnt

    know when

  • 8/14/2019 Delegates and Events.ppt

    4/22

    C# Delegates and Events

    Simple Delegate Command Pattern

    Delegate Host Class

    (Publisher)

    Exposed Delegate

    Knows when the

    event happens but

    doesnt know what to

    do about it

    Delegate User Class

    (Subscriber)

    Knows what to do

    when an event

    happens but doesnt

    know when

    Subscribing Method

    AKA: The Observer Pattern or .NET Event Model

  • 8/14/2019 Delegates and Events.ppt

    5/22

    C# Delegates and Events

    Two reasons to use Delegates

    When youre not sure what should happenwhen an event occurs GUI events

    Threading situations

    Callbacks

    Command Pattern

    To keep your interface clean Looser coupling

  • 8/14/2019 Delegates and Events.ppt

    6/22

    C# Delegates and Events

    Defining and using Delegates

    three steps:

    1. Declaration

    2. Instantiation3. Invocation

  • 8/14/2019 Delegates and Events.ppt

    7/22

    C# Delegates and Events

    Delegate Declarationnamespace some_namespace

    {

    delegate void MyDelegate(int x, int y);

    class MyClass

    {

    public delegate int AnotherDelegate(object o, int y);

    }

    }

    Delegate Type Name

  • 8/14/2019 Delegates and Events.ppt

    8/22

    C# Delegates and Events

    Delegate Instantiationdelegate void MyDelegate(int x, int y);

    class MyClass

    {

    private MyDelegate myDelegate = new MyDelegate( SomeFun );

    public static void SomeFun(int dx, int dy)

    {

    }

    }

    Invocation Method

    Invocation Methodname (no params

    or perens)

  • 8/14/2019 Delegates and Events.ppt

    9/22

    C# Delegates and Events

    More Realisticallyclass MyClass

    {

    private MyDelegate myDelegate;

    public MyDelegate MyDelegate

    {

    set { this.myDelegate = value; }}

    }

    class MainClass{

    [STAThread]

    static void Main()

    {MyClass mc = new MyClass();

    mc.MyDelegate = new MyDelegate( MainClassMethod );

    }

    private static void MainClassMethod(int x, int y) { }

    }

    Delegate Variable (null)

    Passed in and assigned

    in the constructor

  • 8/14/2019 Delegates and Events.ppt

    10/22

    C# Delegates and Events

    Instance Methodsclass MyClass

    {

    private MyDelegate myDelegate;

    public MyDelegate MyDelegate

    {

    set { this.MyDelegate = value; }

    }}

    class MainClass{

    [STAThread]

    static void Main(){

    MainClass mainClass = new MainClass();MyClass mc = new MyClass();

    mc.MyDelegate = new MyDelegate( mainClass.MainClassMethod );}

    private void MainClassMethod(int x, int y) { }

    }

    Method attached to

    an instance

  • 8/14/2019 Delegates and Events.ppt

    11/22

    C# Delegates and Events

    Delegate-Method Compatibility

    A Method is compatible with a Delegate if

    They have the same parameters

    They have the same return type

  • 8/14/2019 Delegates and Events.ppt

    12/22

    C# Delegates and Events

    Delegate Invocationclass MyClass

    {

    private MyDelegate myDelegate;

    public MyClass(MyDelegate myDelegate)

    {

    this.MyDelegate = myDelegate;}

    private void WorkerMethod()

    {int x = 500, y = 1450;

    if(myDelegate != null)

    myDelegate(x, y);}

    }

    Attempting to invoke a delegate instance whose value is null results in an exception of type

    System.NullReferenceException.

  • 8/14/2019 Delegates and Events.ppt

    13/22

    C# Delegates and Events

    Delegates Multicast Nature

    Delegate is really an array of function pointers

    Now when Invoked, mc.MyDelegate will execute allthree Methods

    Notice that you dont have to instantiate the delegatebefore using += The compiler does it for you when calling +=

    mc.MyDelegate += new MyDelegate( mc.Method1 );

    mc.MyDelegate += new MyDelegate( mc.Method2 );

    mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 );

  • 8/14/2019 Delegates and Events.ppt

    14/22

    C# Delegates and Events

    The Invocation List Methods are executed in the order they are added

    Add methods with + and +=

    Remove methods with - and -= Attempting to remove a method that does not exist is not an error

    Return value is whatever the last method returns

    A delegate may be present in the invocation list more than once The delegate is executed as many times as it appears (in the appropriate

    order)

    Removing a delegate that is present more than once removes only the lastoccurrence

  • 8/14/2019 Delegates and Events.ppt

    15/22

    C# Delegates and Events

    Multicast example

    mc.MyDelegate = new MyDelegate( mc.Method1 );

    mc.MyDelegate += new MyDelegate( mc.Method2 );

    mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 );

    // The call to:

    mc.MyDelegate(0, 0);

    // executes:

    // mc.Method1

    // mc.Method2// mc.Method3 (See Delegates Demo)

  • 8/14/2019 Delegates and Events.ppt

    16/22

    C# Delegates and Events

    System.Delegate

    abstract

    Special Only the system and compiler can inherit fromSystem.Delegate

    Members: Method

    Returns A MethodInfo object

    Target

    The this pointer belonging to the method null if the method was static

    operator == and operator !=

  • 8/14/2019 Delegates and Events.ppt

    17/22

    C# Delegates and Events

    System.MulticastDelegate

    Target

    Method

    operator== and operator !=_prev

    Linked list of System.Delegateobjects

    GetInvocationList() Returns the Invocation List as a Delegate[]

  • 8/14/2019 Delegates and Events.ppt

    18/22

    C# Delegates and Events

    Delegate Dangers

    Exposing a delegate might be bad if:

    You dont want others to invoke your delegate

    You have assigned to the delegate internally

    Enter the event keyword...

  • 8/14/2019 Delegates and Events.ppt

    19/22

    C# Delegates and Events

    Events Events are safe delegates

    But they are delegates

    Restricts use of the delegate (event) to the target of a += or -=operation No assignment

    No invocation No access of delegate members (like GetInvocation List)

    Allow for their own Exposure Event Accessors

  • 8/14/2019 Delegates and Events.ppt

    20/22

    C# Delegates and Events

    Event Accessorspublic delegate void FireThisEvent();class MyEventWrapper

    {

    private event FireThisEvent fireThisEvent;

    public void OnSomethingHappens()

    {if(fireThisEvent != null)

    fireThisEvent();

    }

    public event FireThisEvent FireThisEvent

    {

    add { fireThisEvent += value; }remove { fireThisEvent -= value; }

    }

    }

    add and remove

    keywords

    (See Event Demo)

  • 8/14/2019 Delegates and Events.ppt

    21/22

    C# Delegates and Events

    On Word on Exceptions

    Exceptions thrown from a delegate:

    Are thrown to the calling context

    All subsequent delegates in the Invocation List are ignored

  • 8/14/2019 Delegates and Events.ppt

    22/22

    C# Delegates and Events

    Library Delegates ThreadStart

    TimerCallback

    ASyncCallback

    EventHandler

    KeyPressEventHandler KeyEventHandler

    etc.