0% found this document useful (0 votes)
77 views17 pages

Delegates and Events: Hussam Abu-Libdeh CS 2026, Spring 2009

This document summarizes a lecture on delegates and events in C#. It introduces delegates as a way to treat functions as first-class objects that can be passed to other functions. Anonymous methods allow creating methods without names. Events allow classes to raise notifications when something happens by invoking any handlers that have been attached. Delegates and events provide a way to implement asynchronous event-driven programming in C#.

Uploaded by

Saagar Minocha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views17 pages

Delegates and Events: Hussam Abu-Libdeh CS 2026, Spring 2009

This document summarizes a lecture on delegates and events in C#. It introduces delegates as a way to treat functions as first-class objects that can be passed to other functions. Anonymous methods allow creating methods without names. Events allow classes to raise notifications when something happens by invoking any handlers that have been attached. Delegates and events provide a way to implement asynchronous event-driven programming in C#.

Uploaded by

Saagar Minocha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

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 System.Delegate

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;
Console.WriteLine(f1(x));
Console.WriteLine(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){
result.Add(f(element));
}
returnresult;
}

Mapper.cs

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
OuterVariables.cs

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. Button.OnClick

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

You might also like