Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates,...

23
Module 8: Delegates and Events

Transcript of Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates,...

Page 1: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Module 8: Delegates and Events

Page 2: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Overview

Delegates

Multicast Delegates

Events

When to Use Delegates, Events, and Interfaces

Page 3: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Delegates

Delegate Scenario

Declaring a Delegate

Instantiating a Delegate

Calling a Delegate

Page 4: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Delegate Scenario

1 - Change in switch position invokes switch’s OnFlip method

2 - OnFlip Method invokes delegate

3 - Delegate invokes light’s OnFlipCallback method

4 - OnFlipCallback method changes light’s state

OnFlip method

Switch Object

OnFlipCallbackmethod

Light Object

Delegate objectDelegate object

OnFlip method

Switch Object

Page 5: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Declaring a Delegate

A Delegate Declaration Defines a Type That Encapsulates a Method with a Particular Set of Arguments and Return Type

// declares a delegate for a method that takes a single// argument of type string and has a void return type delegate void MyDelegate1(string s);

// declares a delegate for a method that takes a single// argument of type string and has a void return type delegate void MyDelegate1(string s);

Page 6: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Instantiating a Delegate

A Delegate Object Is Created with the new Operator

Delegate Objects Are Immutable

// instantiating a delegate to a static method Hello// in the class MyClassMyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to an instance method// AMethod in object pMyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);

// instantiating a delegate to a static method Hello// in the class MyClassMyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to an instance method// AMethod in object pMyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);

Page 7: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Calling a Delegate

Use a Statement Containing:

The name of the delegate object

Followed by the parenthesized arguments to be passed to the delegate

// given the previous delegate declaration and// instantiation, the following invokes MyClass'// static method Hello with the parameter "World"

a("World");

// given the previous delegate declaration and// instantiation, the following invokes MyClass'// static method Hello with the parameter "World"

a("World");

Page 8: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Demonstration: Using Delegates

Page 9: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Multicast Delegates

Multicast Delegate Scenario

Single vs. Multicast Delegates

Creating and Invoking Multicast Delegates

C# Language-Specific Syntax

Delegate Details

Page 10: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Multicast Delegate Scenario

2 - OnFlip method invokes multicast delegate1

4 - OnFlipCallback method changes light1’s state

3 - delegate1 invokes light1’s OnFlipCallback

7 - OnFlipCallback method changes light2’s state

6 - delegate2 invokes light2’s OnFlipCallback

OnFlip method

Switch Object

OnFlipCallbackmethod

Light1 Object

OnFlipCallbackmethod

Light2 Object

Multicast delegate1 objectMulticast delegate1 object

Multicast delegate2 objectMulticast delegate2 object

Invocation list

5 - delegate2 is invoked

1 - Change in switch position invokes switch’s OnFlip method

OnFlip method

Switch Object

Page 11: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Single vs. Multicast Delegates

All Delegates Have an Invocation List of Methods That Are Executed When Their Invoke Method is Called

Single-Cast Delegates: Derived Directly From System.Delegate

Invocation list contains only one method Multicast Delegates: Derived from System.MulticastDelegate

Invocation list may contain multiple methods Multicast delegates contain two static methods to add and remove references

from invocation list: Combine and Remove

Use GetInvocationList to Obtain an Invocation List as an Array of Delegate References

Use a Delegate’s Target and Method Properties to Determine:

Which object will receive the callback Which method will be called

Page 12: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Creating and Invoking Multicast Delegates

// assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b);  // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a);  // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList();for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) {

((MyDelegate2) DelegateList[i])();}

}

// assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b);  // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a);  // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList();for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) {

((MyDelegate2) DelegateList[i])();}

}

Page 13: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

C# Language-Specific Syntax

C# Delegates That Return Void Are Multicast Delegates

In C#, Use the + and - Operators to Add and Remove Invocation List Entries

Less verbose than Combine and Remove methods

MyDelegate a, b, c, d;a = new MyDelegate(Foo);b = new MyDelegate(Bar);c = a + b; // Compose two delegates to make anotherd = c - a; // Remove a from the composed delegatea += b; // Add delegate b to a's invocation lista -= b; // Remove delegate b from a's list

MyDelegate a, b, c, d;a = new MyDelegate(Foo);b = new MyDelegate(Bar);c = a + b; // Compose two delegates to make anotherd = c - a; // Remove a from the composed delegatea += b; // Add delegate b to a's invocation lista -= b; // Remove delegate b from a's list

Page 14: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Demonstration: Multicast Delegates

Page 15: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Delegate Details

A Delegate Declaration Causes the Compiler to Generate a New Class

// delegate void MyDelegate3(string val);  class MyDelegate3 : System.MulticastDelegate {

public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //...} public void virtual Invoke(string val) { //... }

};

// delegate void MyDelegate3(string val);  class MyDelegate3 : System.MulticastDelegate {

public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //...} public void virtual Invoke(string val) { //... }

};

Page 16: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Events

Declaring an Event

Connecting to an Event

Raising an Event

.NET Framework Guidelines

Page 17: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Declaring an Event

Declare the Delegate Type for the Event

Declare the Event

Like the field of delegate type preceded by an event keyword

// MouseClicked delegate declaredpublic delegate void MouseClickedEventHandler();

public class Mouse {

// MouseClicked event declaredpublic static event MouseClickedEventHandler

MouseClickedHandler;//...

}

// MouseClicked delegate declaredpublic delegate void MouseClickedEventHandler();

public class Mouse {

// MouseClicked event declaredpublic static event MouseClickedEventHandler

MouseClickedHandler;//...

}

Page 18: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Connecting to an Event

Connect by Combining Delegates

Disconnect by Removing Delegates

// Client’s method to handle the MouseClick eventprivate void MouseClicked() { //...}//...

// Client code to connect to MouseClicked event Mouse.MouseClickedHandler += new

MouseClickedEventHandler(MouseClicked);

// Client code to break connection to MouseClick eventMouse.MouseClickedHandler -= new

MouseClickedEventHandler(MouseClicked);

// Client’s method to handle the MouseClick eventprivate void MouseClicked() { //...}//...

// Client code to connect to MouseClicked event Mouse.MouseClickedHandler += new

MouseClickedEventHandler(MouseClicked);

// Client code to break connection to MouseClick eventMouse.MouseClickedHandler -= new

MouseClickedEventHandler(MouseClicked);

Page 19: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Raising an Event

Check Whether Any Clients Have Connected to This Event

If the event field is null, there are no clients

Raise the Event by Invoking the Event’s Delegate

if (MouseClickedHandler != null) MouseClickedHandler();

if (MouseClickedHandler != null) MouseClickedHandler();

Page 20: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Name Events with a Verb and Use Pascal Casing

Use "Raise" for Events, Instead of "Fire"

Event Argument Classes Extend System.EventArgs

Event Delegates Return Void and Have Two Arguments

Use a Protected Virtual Method to Raise Each Event

public class SwitchFlippedEventArgs : EventArgs { //... }

public delegate void SwitchFlippedEventHandler(object sender, SwitchFlippedEventArgs e);

public event SwitchFlippedEventHandler SwitchFlippedHandler;

public class SwitchFlippedEventArgs : EventArgs { //... }

public delegate void SwitchFlippedEventHandler(object sender, SwitchFlippedEventArgs e);

public event SwitchFlippedEventHandler SwitchFlippedHandler;

.NET Framework Guidelines

Page 21: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

When to Use Delegates, Events, and Interfaces

Use a Delegate If:

You basically want a C-style function pointer

You want single callback invocation

The callback should be registered in the call or at construction time, not through methods

Use Events If:

Client signs up for the callback function through methods

More than one object will care

Use an Interface If:

The callback function entails complex behavior, such as multiple methods

Page 22: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Lab 8: Creating a Simple Chat Server

Page 23: Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Review

Delegates

Multicast Delegates

Events

When to Use Delegates, Events, and Interfaces