C# Program to Implement Arithmetic Operations using Delegates

This is a C# Program to implement arithmetic operations using delegates.

Problem Description

This C# Program Implements Arithmetic Operations using Delegates.

Problem Solution

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.

Program/Source Code

Here is source 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.

/*
 *  C# Program to Implement Arithmetic Operations using Delegates
 */
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();
        }
    }
}
Program Explanation

This C# program is used to implement 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. Print the arithmetic operation values.

advertisement
advertisement
Runtime Test Cases
 
Value of Num: 35
Value of Num: 175

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.