C# program to call math operations using delegates

Here, we are going to learn how to call math operations using delegates in C#?
Submitted by Nidhi, on September 15, 2020

Here we will create a class MathClass and bind the methods of delegate and call method of MethodClass.

Program:

The source code to call math operations using delegates is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to call math operations using delegates.

using System;

delegate int MyDel(int num);

public class MathClass
{
    public static int Qube(int num)
    {
        return num*num*num;
    }

    public static int Square(int num)
    {
        return num*num;
    }
}

class Sample 
{
    static void Main()
    {
        MyDel[] opers = { MathClass.Square,MathClass.Qube };
        int result = 0;

        for (int i = 0; i < opers.Length; i++)
        {
            result = opers[i](10);
            Console.WriteLine("Operation[{0}]:", i);
            Console.WriteLine("\tResult: "+result);
        }
    }
}

Output:

Operation[0]:
        Result: 100
Operation[1]:
        Result: 1000
Press any key to continue . . .

Explanation:

In the above program, we created two classes MathClass and Sample. The MathClass contains two static methods Qube() and Square().

In the Main() method, we created the array of delegates initialized with Square() and Qube() method.

for (int i = 0; i < opers.Length; i++)
{
    result = opers[i](10);
    Console.WriteLine("Operation[{0}]:", i);
    Console.WriteLine("\tResult: "+result);
}

Here we called both methods using an array of delegates and print the result on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.