I was reviewing Andrew Troelsen book on C# 4.0. The part that explains delegates starts as smooth as:
public class SimpleMath
{
//declare delegate
public delegate int BinaryOp(int x, int y);
public static int Add(int x, int y){
return x + y;
}
class Program
{
static void Main(string[] args){
//create delegate which points to Add method
BinaryOp b = new BinaryOp(SimpleMath.Add);
//Invoke Add method using delegate
Console.WriteLine("10 + 10 is {0}", b(10,10));
Console.ReadLine();
}
than gets as complicated as
public class Car
{
public int CurrentSpeed {get;set;}
public int MaxSpeed {get;set;}
private bool carIsDead {get;set;}
public Car() {MaxSpeed=10;}
public Car(int maxSpeed, int currentSpeed)
{
MaxSpeed = maxSpeed;
CurrentSpeed = currentSpeed;
}
//declare delegate
public delegate void CarEngineHandler(string msgForCaller);
//define member of this delegate
private CarEngineHandler listOfHandlers;
//add registration function for the caller
public void RegisterWithCarEngine(CarEngineHandler methodToCall)
{
listOfHandlers = methodToCall;
}
public void Accelerate(int delta)
{
if (carIsDead)
{
if (listOfHandlers!=null)
listOfHandlers("Sorry, the car is dead");
}
else {
CurrentSpeed+=delta;
if (10== (MaxSpeed - CurrentSpeed) && listOfHandlers!=null)
{
listOfHandlers("Gonna blow!");
}
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("Current Speed = {0}", CurrentSpeed);
}
}
}
If we try to pick that content and teach somebody else, we are going to find a hard time, since it becomes tricky.
How would you teach C# delegates in a way he/she is able to understand clearly when to use them?