You are on page 1of 7

PCS4

Week 2:
About delegates and events (what we did last week),
2 extra examples and
a bit about the week-2-stuff
A delegate stands in for a (mysterious
list of) actual methods
1. Define the prototype (the heading) of the actual methods the
delegate will stand for.
2. Then define a delegate.
3. You can add and remove actual methods the delegate stands for.

Calling the delegate means calling the actual methods.

An event : like a delegate, but better


protected (can only be raised from inside
the class)

2
public class Motorbike Example
{
private int speed, maxSpeed;

public delegate void SpeedChangedHandler


(Motorbike sender, int extraInfo);

public event SpeedChangedHandler SpeedChanged;


public event SpeedChangedHandler SpeedLimitExceeded;

public void Accelerate(int inc)


{ . . . Always check
if (SpeedChanged != null) if the event
{ SpeedChanged(this, this.speed); } exists
. . .
}
}

3
public class Motorbike Example
{

protected void OnSpeedChanged(int inc)


{
if (SpeedChanged != null)
{ SpeedChanged(this, inc); }
}

public void Accelerate(int inc)


{ . . .
OnSpeedChanged(inc);
. . .
}
}

4
In another class:
Example
private void ShowSpeedInPits(Motorbike m, int s) { . . . }

private Motorbike ValentinosBike;

// adding an actual method to an event


ValentinosBike.SpeedChanged +=
new Motorbike.SpeedChangedHandler(this.ShowSpeedInPits);

// removing an actual method from an event


ValentinosBike.SpeedChanged -=
new Motorbike.SpeedChangedHandler(this.ShowSpeedInPits);

5
Today:
1. Extra: How to use a RFID-reader (from Phidgets)
(see next slide and demo)

2. Extra: How to get several buttons on the window


and let them handle their own button-click?
(see demo)

3. How to sort elements of an array (or List, but that is


for the practicum) (see demo)

4. Practicum for this week: work on "deliver some


deliverables" : it is about sorting the elements in a
list.

6
The RFID-reader from Phidgets (phidgets.com)
1. Download the driver (on Phidgets.com ????????? -> 64-bits
installer download) or https://www.phidgets.com/docs/OS_-_Windows,
and install it on your laptop.
2. Start a project in Visual Studio.
3. Add a reference to the dll
( to C:/Program Files/Phidgets/Phidget22/Phidget22.NET.dll )
4. Add using-statements to your VS-project:
using Phidget22;
using Phidget22.Events;

See demo.

You might also like