Write a C# Program to Implement Arithmetic Operations using Delegates

Write a C# Program to Implement Arithmetic Operations using Delegates

This C# Program Implements Arithmetic Operations using Delegates. Here the delegate is a form of type-safe function pointer used by the .NET Framework. Delegates are often used to implement callbacks and event listeners. A delegate does not need to know anything about classes of methods it works with.

Here is code of the C# Program to Implement Arithmetic Operations using Delegates. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

ANS:

using System;
delegate int NumberChanger(int n);
namespace example
{
    class Delegate
    {
        static int num = 10;
        public static int AddNum(int a)
        {
            num += a;
            return num;
        }

        public static int MultNum(int b)
        {
            num *= b;
            return num;
        }
        public static int getNum()
        {
            return num;
        }

        static void Main(string[] args)
        {

            NumberChanger n1 = new NumberChanger(AddNum);
            NumberChanger n2 = new NumberChanger(MultNum);
            n1(25);
            Console.WriteLine("Value of Num: {0}", getNum());
            n2(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}

Output:

Value of Num: 35

Value of Num: 175.

Post a Comment

Previous Post Next Post