Delegates and Events
Hussam Abu-Libdeh
CS 2026, Spring 2009
Announcements
Homework assignment due today
Submit in CMS
Only upload you .cs C# source code file
Previously Covered
Function parameters: ref,out,params
Iterators
Advanced C# topics:
Nullable types
Partial Classes
Generics
Today's Agenda
Delegates
Anonymous methods
Events
Motivation Function Pointers
Treat functions as first-class objects
Pass functions to other functions
Ocaml:
map(funx>x*x)[1;2;3];;
C/C++:
typedefint(*fptr)(int);
intapply(fptrf,intvar){
returnf(var);
}
intF(intvar){..}
fptrf=F;
apply(f,10);//sameasF(10)
Delegates
An objectified function
Is a type that references a method
Behaves like a C/C++ function pointer
Inherits from [Link]
Sealed implicitly
i.e. It can not be inherited from
e.g. delegateintFoo(intx)
defines a new type Foo, takes int,
returns int
Delegates Example
delegateintFoo(refintx);
intIncrement(refintx){returnx++;}
intDecrement(refintx){returnx;}
Foof1=newFoo(Increment);
f1+=Decrement;
x=10;
[Link](f1(x));
[Link](x);
Delegate calls methods in order
ref values updated between calls
return value is the value of the last call
Delegates Usage Pattern
Declared like a function
Instantiated like a reference type
Takes a method parameter in constructor
Modified with +, -, +=, -=
Can add multiple instances of a method
Removes the last instance of the method
in the list
Called like a function
Invoking a delegate that has not been
assigned a list of methods causes an
exception
List Mapping Example
delegateintFoo(intx);
List<int>Map(Foof,List<int>list){
List<int>result=newList<int>();
foreach(intelementinlist){
[Link](f(element));
}
returnresult;
}
[Link]
Anonymous Methods
//fisadelegate
inty=10;
f+=delegate(intx){returnx+y;}
Creates a method and adds it to delegate
Treated the same as other methods
Variables captured by anonymous method
Outer variables
e.g. y in the previous example
Outer Variables
Local variables declared outside the
scope of an anonymous method
Captured & remain for the lifetime of the
delegate
Outer variables values are captured once
per delegate
[Link]
Events Motivation
Event-based programming
Events are raised by run-time
Client code registers event handles to be
invoked
Indirectly through external actions,
function calls
Also called callbacks
Allows asynchronous computation
e.g. GUI programming
Events in C#
In C#
Events; special delegates
Event handles; functions
Created from delegates using event
keyword
Declares a class member, enabling the
class to raise events (i.e. to invoke the
event delegate)
Events Example
publicdelegatevoidEventHandler(objectsource,
EventArgse);
classRoom{
publiceventEventHandlerEnter;
publicvoidRegisterGuest(objectsource,
EventArgse){..}
publicstaticvoidMain(string[]args){
Enter+=newEventHandler(RegisterGuest);
if(Enter!=null){
Enter(this,newEventArgs());
}
}
}
Events Usage Pattern
Enter is an object of type delegate
When event is raised each delegate
called
C# allows any delegate to be attached to
an event
Events vs Delegates
Differences from regular delegates
Delegates can not be declared in
interfaces; events can
Can only raise an event in its defining a
class
Outside can only do += and -=
To raise events from outside the class
Normally methods are used
e.g. [Link]
Events Accessors
add and remove accessors
Like get and set for properties
Invoked by += and -= operations
Can be explicitly defined for events
Normally generated by compiler
Example
When you want to control the space used
for storage
Or to control accessibility