CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
10 + 10 is 20
Note The SimpleDelegate project is located under the Chapter 10 subdirectory.
Sending Object State Notifications Using Delegates
Clearly, the previous SimpleDelegate example was intended to be purely illustrative in nature, given that
there would be no compelling reason to define a delegate simply to add two numbers. To provide a more
realistic use of delegate types, let’s use delegates to define a Car class that has the ability to inform
external entities about its current engine state. To do so, we will take the following steps:
1.
Define a new delegate type that will be used to send notifications to the caller.
2.
Declare a member variable of this delegate in the Car class.
3.
Create a helper function on the Car that allows the caller to specify the method
to call back on.
4.
Implement the Accelerate() method to invoke the delegate’s invocation list
under the correct circumstances.
To begin, create a new Console Application project named CarDelegate. Now, define a new Car class
that looks initially like this:
public class Car
{
// Internal state data.
public int CurrentSpeed { get; set; }
public int MaxSpeed { get; set; }
public string PetName { get; set; }
// Is the car alive or dead?
private bool carIsDead;
}
// Class constructors.
public Car() { MaxSpeed = 100; }
public Car(string name, int maxSp, int currSp)
{
CurrentSpeed = currSp;
MaxSpeed = maxSp;
PetName = name;
}
Now, consider the following updates, which address the first three points:
public class Car
{
...
// 1) Define a delegate type.
367