Skip to main content

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.

  1. Create a new C# Console Application project in Visual Studio.
  2. In the Solution Explorer, right-click on the project name and select "Add" > "Class".
  3. Name the class "DelegateDemo.cs".
  4. Open the "DelegateDemo.cs" file.
  5. 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);
}
}
}
  1. Save the file.

  2. Build and run the project.

  3. 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.