illustrates the use of a multicast delegate : delegate : Language Basics C# Source Code


Custom Search

C# Source Code » Language Basics » delegate »

 

illustrates the use of a multicast delegate









    

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

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example12_2.cs illustrates the use of a multicast delegate
*/

using System;


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


// declare the MotionCalculations class
class MotionCalculations
{

  // FinalSpeed() calculates the final speed
  public static void FinalSpeed(
    double acceleration, double time
  )
  {
    double finalSpeed = acceleration * time;
    Console.WriteLine("finalSpeed = " + finalSpeed +
      " meters per second");
  }

  // Distance() calculates the distance traveled
  public static void Distance(
    double acceleration, double time
  )
  {
    double distance = acceleration * Math.Pow(time, 2) / 2;
    Console.WriteLine("distance = " + distance + " meters");
  }

}


public class Example12_2
{

  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 delegate object that call the
    // MotionCalculations.FinalSpeed() and
    // MotionCalculations.Distance() methods
    DelegateCalculation myDelegateCalculation1 =
      new DelegateCalculation(MotionCalculations.FinalSpeed);
    DelegateCalculation myDelegateCalculation2 =
      new DelegateCalculation(MotionCalculations.Distance);

    // create a multicast delegate object from
    // myDelegateCalculation1 and
    // myDelegateCalculation2
    DelegateCalculation myDelegateCalculations =
      myDelegateCalculation1 + myDelegateCalculation2;

    // calculate and display the final speed and distance
    // using myDelegateCalculations
    myDelegateCalculations(acceleration, time);

  }

}

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Language Basics
» delegate