Mega Code Archive

 
Categories / C# / Language Basics
 

Illustrates the use of a delegate that calls object methods

/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /*   Example12_3.cs illustrates the use of a delegate   that calls object methods */ using System; // declare the DelegateCalculation delegate class public delegate string DelegateDescription(); // declare the Person class class Person {   // declare two private fields   private string name;   private int age;   // define a constructor   public Person(string name, int age)   {     this.name = name;     this.age = age;   }   // define a method that returns a string containing   // the person's name and age   public string NameAndAge()   {     return(name + " is " + age + " years old");   } } // declare the Car class class Car {   // declare two private fields   private string model;   private int topSpeed;   // define a constructor   public Car(string model, int topSpeed)   {     this.model = model;     this.topSpeed = topSpeed;   }   // define a method that returns a string containing   // the car's model and top speed   public string MakeAndTopSpeed()   {     return("The top speed of the " + model + " is " +       topSpeed + " mph");   } } public class Example12_3 {   public static void Main()   {     // create a Person object named myPerson     Person myPerson = new Person("Jason Price", 32);     // create a delegate object that calls myPerson.NameAndAge()     DelegateDescription myDelegateDescription =       new DelegateDescription(myPerson.NameAndAge);     // call myPerson.NameAndAge() through myDelegateDescription     string personDescription = myDelegateDescription();     Console.WriteLine("personDescription = " + personDescription);     // create a Car object named myCar     Car myCar = new Car("MR2", 140);     // set myDelegateDescription to call myCar.MakeAndTopSpeed()     myDelegateDescription =       new DelegateDescription(myCar.MakeAndTopSpeed);     // call myCar.MakeAndTopSpeed() through myDelegateDescription     string carDescription = myDelegateDescription();     Console.WriteLine("carDescription = " + carDescription);   } }