We define a delegate for arithmetic operations. This delegate is used as first parameter of Calculate method. The parameter can accept a method definition as argument. We can use Lambda expression for method also.
public delegate int ArithmeticOperation(int number1, int number2);
static class Calculator
{
public static int Calculate(ArithmeticOperation operation, int number1, int number2)
{
try
{
int total = operation.Invoke(number1, number2);
return total;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
return 0;
}
}
}Lambda expression is used as delegate argument for Calculate method in client Program class Main method. class Program
{
static void Main(string[] args)
{
int sum = Calculator.Calculate((x, y) => (x + y), 100, 5);
int difference = Calculator.Calculate((x, y) => (x - y), 100, 5);
int product = Calculator.Calculate((x, y) => (x * y), 100, 5);
int division = Calculator.Calculate((x, y) => (x / y), 100, 5);
Console.WriteLine("+ Result is " + sum);
Console.WriteLine("- Result is " + difference);
Console.WriteLine("* Result is " + product);
Console.WriteLine("/ Result is " + division);
Console.ReadLine();
}
}
Result:+ Result is 105
- Result is 95
* Result is 500
/ Result is 20
No comments:
Post a Comment