Q:

C# program to call math operations using delegates

0

C# program to call math operations using delegates

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now