Practical-05
Problem Statement
Write a program using delegate in which addition and subtraction of two Integer values is possible.
Solution
To solve this problem, we can use C# and demonstrate the usage of delegates to perform addition and subtraction of two integer values.
- Create a new C# Console Application project in Visual Studio.
- In the Solution Explorer, right-click on the project name and select "Add" > "Class".
- Name the class "DelegateDemo.cs".
- Open the "DelegateDemo.cs" file.
- Add the following code to demonstrate the usage of delegates for addition and subtraction:
using System;
namespace DelegateDemo
{
public delegate int MathOperation(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static int Subtract(int a, int b)
{
return a - b;
}
static void Main(string[] args)
{
MathOperation addDelegate = new MathOperation(Add);
MathOperation subtractDelegate = new MathOperation(Subtract);
int num1 = 10;
int num2 = 5;
int sum = addDelegate(num1, num2);
int difference = subtractDelegate(num1, num2);
Console.WriteLine("Sum: " + sum);
Console.WriteLine("Difference: " + difference);
}
}
}
-
Save the file.
-
Build and run the project.
-
The console application will display the following output:
Sum: 15
Difference: 5
This completes the solution to the problem.
Summary
In this practical, we learned how to use delegates in C# to perform addition and subtraction of two integer values.