illustrates the use of a delegate 2

image_pdfimage_print

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example12_1.cs illustrates the use of a delegate
*/

using System;


// declare the DelegateCalculation delegate class
public delegate double DelegateCalculation(
  double acceleration, double time
);


// declare the MotionCalculations class
class MotionCalculations
{

  // FinalSpeed() calculates the final speed
  public static double FinalSpeed(
    double acceleration, double time
  )
  {
    double finalSpeed = acceleration * time;
    return finalSpeed;
  }

  // Distance() calculates the distance traveled
  public static double Distance(
    double acceleration, double time
  )
  {
    double distance = acceleration * Math.Pow(time, 2) / 2;
    return distance;
  }

}


public class Example12_1
{

  public static void Main()
  {

    // declare and initialize the acceleration and time
    double acceleration = 10;  // meters per second per second
    double time = 5;  // seconds
    Console.WriteLine("acceleration = " + acceleration +
      " meters per second per second");
    Console.WriteLine("time = " + time + " seconds");

    // create a delegate object that calls
    // MotionCalculations.FinalSpeed
    DelegateCalculation myDelegateCalculation =
      new DelegateCalculation(MotionCalculations.FinalSpeed);

    // calculate and display the final speed
    double finalSpeed = myDelegateCalculation(acceleration, time);
    Console.WriteLine("finalSpeed = " + finalSpeed +
      " meters per second");

    // set the delegate method to MotionCalculations.Distance
    myDelegateCalculation =
      new DelegateCalculation(MotionCalculations.Distance);

    // calculate and display the distance traveled
    double distance = myDelegateCalculation(acceleration, time);
    Console.WriteLine("distance = " + distance + " meters");

  }

}