C# program to call math operations using delegates

Here, we are going to learn how to call math operations using delegates in C#? By Nidhi Last updated : April 03, 2023

C# Math Operations Using Delegates

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

C# code for math operations using delegates

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.

C# Delegate Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.