The Simplest Possible Delegate Example
namespace SimpleDelegate
{
public delegate int BinaryOp(int x, int y);
public class SimpleMath
{
public static int Add(int x, int y)
{ return x + y; }
public static int Subtract(int x, int y)
{ return x – y; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Simple Delegate Example *****n");
// Create a BinaryOp object that
// "points to" SimpleMath.Add().
BinaryOp b = new BinaryOp(SimpleMath.Add);
// Invoke Add() method using delegate.
Console.WriteLine("10 + 10 is {0}", b(10, 10));
BinaryOp b2 = new BinaryOp(SimpleMath. Subtract);
Console.WriteLine("10 - 10 is {0}", b2(10, 10));
Console.ReadLine();
}
}
}
Investigating a Delegate Object
• by creating a helper function named DisplayDelegateInfo().
• This method will print out names of the methods maintained by the incoming
System.Delegate derived type as well as the name of the class defining the method.
• To do so, we will iterate over the System.Delegate array returned by GetInvocationList(),
invoking each object’s Target and Method properties:
static void DisplayDelegateInfo(Delegate delObj)
{
// Print the names of each member in the
// delegate's invocation list.
foreach (Delegate d in delObj.GetInvocationList())
{
Console.WriteLine("Method Name: {0}", d.Method);
Console.WriteLine("Type Name: {0}", d.Target);
}
}
Car Type with Delegates
• Define the AboutToBlow and Exploded delegates.
• Declare member variables of each delegate type in the Car class.
• Create helper functions on the Car that allow the caller to specify the
methods maintained by the delegate member variables.
• Update the Accelerate() method to invoke the delegate’s invocation
list under the correct circumstances.
public class Car
{
// Define the delegate types.
public delegate void AboutToBlow(string msg);
public delegate void Exploded (string msg);
// Define member variables of each delegate type.
private AboutToBlow almostDeadList;
private Exploded explodedList;
// Add members to the invocation lists using helper methods.
public void OnAboutToBlow(AboutToBlow clientMethod)
{ almostDeadList = clientMethod; }
public void OnExploded(Exploded clientMethod)
{ explodedList = clientMethod; }
...
}
public void Accelerate(int delta)
{
if (carIsDead){
if (explodedList != null)
explodedList("Sorry, this car is dead...");}
else{
currSpeed += delta;
if (10 == maxSpeed - currSpeed
&& almostDeadList != null){
almostDeadList("Careful buddy! Gonna blow!");}
if (currSpeed >= maxSpeed)
carIsDead = true;
else
Console.WriteLine("->CurrSpeed = {0}", currSpeed);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Delegates as event enablers *****");
// Make a car as usual.
Car c1 = new Car("SlugBug", 100, 10);
// Register event handlers with Car type.
c1.OnAboutToBlow(new Car.AboutToBlow(CarAboutToBlow));
c1.OnExploded(new Car.Exploded(CarExploded));
Console.WriteLine("n***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
}
// The Car will call these methods.
public static void CarAboutToBlow(string msg)
{ Console.WriteLine(msg); }
public static void CarExploded(string msg)
{ Console.WriteLine(msg); }
}
A More Elaborate Delegate Example
// Updated Car class.
public class Car
{
…
// Are we in need of a wash? Need to rotate tires?
private bool isDirty;
private bool shouldRotate;
// Extra params to set bools.
public Car(string name, int max, int curr,
bool washCar, bool rotateTires){
...
isDirty = washCar;
shouldRotate = rotateTires;}
public bool Dirty{
get{ return isDirty; }
set{ isDirty = value; }}
}
public bool Rotate
{
get{ return shouldRotate; }
set{ shouldRotate = value; }
}
}
Now, also assume the Car type nests a new delegate, CarDelegate:
// Car defines yet another delegate.
public class Car
{
...
// Can call any method taking a Car as
// a parameter and returning nothing.
public delegate void CarDelegate(Car c);
...
}
Delegates As Parameters
Using System.Collections;
...
public class Garage
{
...
// This method takes a Car.CarDelegate as a parameter.
public void ProcessCars(Car.CarDelegate proc)
{
// Where are we forwarding the call?
Console.WriteLine("***** Calling: {0} *****",
proc.Method);
// Are we calling an instance method or a static method?
if(proc.Target != null)
Console.WriteLine("—>Target: {0} ", proc.Target);
else
Console.WriteLine("—>Target is a static method");
// Call the method "pointed to," passing in each car.
foreach (Car c in theCars)
{
Console.WriteLine("n-> Processing a Car");
proc(c);
}
}
}

The C# programming laguage delegates notes Delegates.pptx

  • 1.
    The Simplest PossibleDelegate Example namespace SimpleDelegate { public delegate int BinaryOp(int x, int y); public class SimpleMath { public static int Add(int x, int y) { return x + y; } public static int Subtract(int x, int y) { return x – y; } }
  • 2.
    class Program { static voidMain(string[] args) { Console.WriteLine("***** Simple Delegate Example *****n"); // Create a BinaryOp object that // "points to" SimpleMath.Add(). BinaryOp b = new BinaryOp(SimpleMath.Add); // Invoke Add() method using delegate. Console.WriteLine("10 + 10 is {0}", b(10, 10)); BinaryOp b2 = new BinaryOp(SimpleMath. Subtract); Console.WriteLine("10 - 10 is {0}", b2(10, 10)); Console.ReadLine(); } } }
  • 3.
    Investigating a DelegateObject • by creating a helper function named DisplayDelegateInfo(). • This method will print out names of the methods maintained by the incoming System.Delegate derived type as well as the name of the class defining the method. • To do so, we will iterate over the System.Delegate array returned by GetInvocationList(), invoking each object’s Target and Method properties: static void DisplayDelegateInfo(Delegate delObj) { // Print the names of each member in the // delegate's invocation list. foreach (Delegate d in delObj.GetInvocationList()) { Console.WriteLine("Method Name: {0}", d.Method); Console.WriteLine("Type Name: {0}", d.Target); } }
  • 4.
    Car Type withDelegates • Define the AboutToBlow and Exploded delegates. • Declare member variables of each delegate type in the Car class. • Create helper functions on the Car that allow the caller to specify the methods maintained by the delegate member variables. • Update the Accelerate() method to invoke the delegate’s invocation list under the correct circumstances.
  • 5.
    public class Car { //Define the delegate types. public delegate void AboutToBlow(string msg); public delegate void Exploded (string msg); // Define member variables of each delegate type. private AboutToBlow almostDeadList; private Exploded explodedList; // Add members to the invocation lists using helper methods. public void OnAboutToBlow(AboutToBlow clientMethod) { almostDeadList = clientMethod; } public void OnExploded(Exploded clientMethod) { explodedList = clientMethod; } ... }
  • 6.
    public void Accelerate(intdelta) { if (carIsDead){ if (explodedList != null) explodedList("Sorry, this car is dead...");} else{ currSpeed += delta; if (10 == maxSpeed - currSpeed && almostDeadList != null){ almostDeadList("Careful buddy! Gonna blow!");} if (currSpeed >= maxSpeed) carIsDead = true; else Console.WriteLine("->CurrSpeed = {0}", currSpeed); } }
  • 7.
    class Program { static voidMain(string[] args) { Console.WriteLine("***** Delegates as event enablers *****"); // Make a car as usual. Car c1 = new Car("SlugBug", 100, 10); // Register event handlers with Car type. c1.OnAboutToBlow(new Car.AboutToBlow(CarAboutToBlow)); c1.OnExploded(new Car.Exploded(CarExploded)); Console.WriteLine("n***** Speeding up *****"); for (int i = 0; i < 6; i++) c1.Accelerate(20); Console.ReadLine(); }
  • 8.
    // The Carwill call these methods. public static void CarAboutToBlow(string msg) { Console.WriteLine(msg); } public static void CarExploded(string msg) { Console.WriteLine(msg); } }
  • 9.
    A More ElaborateDelegate Example // Updated Car class. public class Car { … // Are we in need of a wash? Need to rotate tires? private bool isDirty; private bool shouldRotate; // Extra params to set bools. public Car(string name, int max, int curr, bool washCar, bool rotateTires){ ... isDirty = washCar; shouldRotate = rotateTires;} public bool Dirty{ get{ return isDirty; } set{ isDirty = value; }}
  • 10.
    } public bool Rotate { get{return shouldRotate; } set{ shouldRotate = value; } } } Now, also assume the Car type nests a new delegate, CarDelegate: // Car defines yet another delegate. public class Car { ... // Can call any method taking a Car as // a parameter and returning nothing. public delegate void CarDelegate(Car c); ... }
  • 11.
    Delegates As Parameters UsingSystem.Collections; ... public class Garage { ... // This method takes a Car.CarDelegate as a parameter. public void ProcessCars(Car.CarDelegate proc) { // Where are we forwarding the call? Console.WriteLine("***** Calling: {0} *****", proc.Method); // Are we calling an instance method or a static method? if(proc.Target != null) Console.WriteLine("—>Target: {0} ", proc.Target); else Console.WriteLine("—>Target is a static method");
  • 12.
    // Call themethod "pointed to," passing in each car. foreach (Car c in theCars) { Console.WriteLine("n-> Processing a Car"); proc(c); } } }