Delegates and Events
Delegates and Events
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;
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;
• Method can be static. In this case the class name must be specified instead of obj.
new Notifier(MyClass.StaticSayHello);
4
Multicast Delegates
A delegate variable can hold multiple methods at the same time
Notifier greetings;
greetings = SayHello;
greetings += SayGoodBye;
greetings -= SayHello;
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");
• One needs a class that implements the interface (i.e. its methods).
• 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();
}
}
8
Example
public delegate void KeyEventHandler (object sender, KeyEventArgs e);
class MyKeyEventSource {
public event KeyEventHandler KeyDown;
...
KeyDown(this, new KeyEventArgs(...));
...
}
class MyKeyListener {
public MyKeyListener(...) { keySource.KeyDown += HandleKey;}
void HandleKey (object sender, KeyEventArgs e) {...}
}