0% found this document useful (0 votes)
26 views2 pages

Delegate

Application

Uploaded by

gadala.suhasini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views2 pages

Delegate

Application

Uploaded by

gadala.suhasini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System;

namespace CalculatorApp
{
// Delegate declaration
public delegate double MathOperation(double num1, double num2);

public class MathOperations


{
// Method to add two numbers
public double Add(double num1, double num2)
{
return num1 + num2;
}

// Method to subtract two numbers


public double Subtract(double num1, double num2)
{
return num1 - num2;
}

// Method to multiply two numbers


public double Multiply(double num1, double num2)
{
return num1 * num2;
}

// Method to divide two numbers


public double Divide(double num1, double num2)
{
if (num2 == 0)
{
throw new DivideByZeroException("Division by zero is not
allowed.");
}
return num1 / num2;
}
}

class Program
{
static void Main(string[] args)
{
MathOperations mathOps = new MathOperations();

// Using delegate to call methods


MathOperation operation;

Console.WriteLine("Choose an operation: +, -, *, /");


string choice = Console.ReadLine();

Console.WriteLine("Enter first number:");


double num1 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter second number:");


double num2 = Convert.ToDouble(Console.ReadLine());

switch (choice)
{
case "+":
operation = mathOps.Add;
break;
case "-":
operation = mathOps.Subtract;
break;
case "*":
operation = mathOps.Multiply;
break;
case "/":
operation = mathOps.Divide;
break;
default:
Console.WriteLine("Invalid operation.");
return;
}

try
{
double result = operation(num1, num2);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

You might also like