0% found this document useful (0 votes)
71 views9 pages

Delegates and Events

The document discusses delegates and events in .NET. Delegates allow assigning methods to variables and invoking them. Events use delegates to notify subscribers when something happens. The document explains how to declare, assign and invoke delegates as well as use them for events.

Uploaded by

api-3734769
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views9 pages

Delegates and Events

The document discusses delegates and events in .NET. Delegates allow assigning methods to variables and invoking them. Events use delegates to notify subscribers when something happens. The document explains how to declare, assign and invoke delegates as well as use them for events.

Uploaded by

api-3734769
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Delegates and Events

© University of Linz, Institute for System Software, 2004


published under the Microsoft Curriculum License
1
Delegate = Method Type
Declaration of a delegate type
delegate void Notifier (string sender); // ordinary method signature
// with the keyword delegate

Declaration of a delegate variable


Notifier greetings;

Assigning a method to a delegate variable


void SayHello(string sender) {
Console.WriteLine("Hello from " + sender);
}

greetings = new Notifier(SayHello); // or just: greetings = SayHello;


// in C# 2.0

Calling a delegate variable


greetings("John"); // invokes SayHello("John") => "Hello from John"

2
Assigning Different Methods
Every matching method can be assigned to a delegate variable
void SayGoodBye(string sender) {
Console.WriteLine("Good bye from " + sender);
}
greetings = SayGoodBye;

greetings("John"); // SayGoodBye("John") => "Good bye from John"

Note
• A delegate variable can have the value null (no method assigned).
• If null, a delegate variable must not be called (otherwise exception).
• Delegate variables are first class objects: can be stored in a data structure, passed as a
parameter, etc.

3
Creating a Delegate Value
m = new DelegateType (obj.Method); // or just: m = obj.Method;

• A delegate variable stores a method and its receiver, but no parameters !


new Notifier(myObj.SayHello);

• obj can be this (and can be omitted)


new Notifier(SayHello);

• Method can be static. In this case the class name must be specified instead of obj.
new Notifier(MyClass.StaticSayHello);

• Method must not be abstract, but it can be virtual, override, or new.

• Method signature must match the signature of the DelegateType


- same number of parameters
- same parameter types (including the return type)
- same parameter kinds (value, ref/out)

4
Multicast Delegates
A delegate variable can hold multiple methods at the same time

Notifier greetings;
greetings = SayHello;
greetings += SayGoodBye;

greetings("John"); // "Hello from John"


// "Good bye from John"

greetings -= SayHello;

greetings("John"); // "Good bye from John"

Note
• If the multicast delegate is a function, the value of the last call is returned
• If the multicast delegate has an out parameter, the parameter of the last call is returned.
ref parameters are passed through all methods.

5
How Can This be Done in Java?
interface Notifier { // corresponds to a delegate type
void greetings(String sender);
}
class HelloSayer implements Notifier { // corresponds to a delegate value
public void greetings (String sender) {
System.out.println("Hello from" + sender);
}
}
Notifier n = new HelloSayer(); // corresponds to the initialization of the delegate variable
n.greetings("John");

• Interfaces takes the role of delegate types.

• One needs a class that implements the interface (i.e. its methods).

• Static methods cannot be modeled as delegates in this way.

• Multicasts require a special mechanism for registering methods and calling them in
sequence.

6
Event = Special Delegate Field
class Model {
public event Notifier notifyViews;
public void Change() { ... notifyViews("Model"); }
}

class View {
public View(Model m) { m.notifyViews += Update; }
void Update(string sender) { Console.WriteLine(sender + " was changed"); }
}

class Test {
static void Main() {
Model model = new Model();
new View(model); new View(model); ...
model.Change();
}
}

Why events instead of normal delegate variables?


• Only the class that declares the event can fire it (better encapsulation)
• Other classes may change event fields only with += or -= (but not with =)
7
Event Handling in the .NET Library
In the .NET library delegates for event handling have the following signature

delegate void SomeEvent (object source, MyEventArgs e);

• Result type: void


• 1. parameter: Sender of the event (type object)
• 2. parameter: event (subclass of System.EventArgs)

public class EventArgs {


public static readonly EventArgs Empty;
}

8
Example
public delegate void KeyEventHandler (object sender, KeyEventArgs e);

public class KeyEventArgs : EventArgs {


public virtual bool Alt { get {...} } // true if Alt key was pressed
public virtual bool Shift { get {...} } // true if Shift key was pressed
public bool Control { get {...} } // true if Ctrl key was pressed
public bool Handled { get{...} set {...} } // indicates if event was already handled
public int KeyValue { get {...} } // the typed keyboard code
...
}

class MyKeyEventSource {
public event KeyEventHandler KeyDown;
...
KeyDown(this, new KeyEventArgs(...));
...
}

class MyKeyListener {
public MyKeyListener(...) { keySource.KeyDown += HandleKey;}
void HandleKey (object sender, KeyEventArgs e) {...}
}

You might also like