Monday, 15 February 2016

C# Program how to Call Math Operations with Delegates

using System;
public class MathOperationsWithDelegate
{
    public static double Multiply(double value)
    {
        return value * 2;
    }

    public static double Square(double value)
    {
        return value * value;
    }
}


delegate double DoubleOp(double x);

class Application
{
    static void Main()
    {
        DoubleOp[] operations =
            {
               MathOperationsWithDelegate.Multiply,
               MathOperationsWithDelegate.Square
            };

        for (int i = 0; i < operations.Length; i++)
        {
            Console.WriteLine("Operation[{0}]:", i);
            ProcessAndDisplayNumber(operations[i], 3.0);
            ProcessAndDisplayNumber(operations[i], 11.44);
            ProcessAndDisplayNumber(operations[i], 1.732);
            Console.WriteLine();
        }
        Console.ReadLine();
    }

    static void ProcessAndDisplayNumber(DoubleOp action, double value)
    {
        double result = action(value);
        Console.WriteLine(
           "Value : {0}  Result : {1}", value, result);
    }
}
---------------
OUTPUT:-

Operation[0]:
Value : 3  Result : 6
Value : 11.44  Result : 22.88
Value : 1.732  Result : 3.464

Operation[1]:
Value : 3  Result : 9
Value : 11.44  Result : 130.8736
Value : 1.732  Result : 2.999824
----------------------------------------------

No comments:

Post a Comment