Q:

C# program to return the value from the method using a delegate

belongs to collection: C# Delegate Programs

0

C# program to return the value from the method using a delegate

All Answers

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

Program:

The source code to return the value from the method using delegate is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to return the value from a method using a delegate.

using System;

delegate int MyDel(int num);
class Sample
{ 
    static int CalculateFactorial(int num)
    {
        int fact = 1;

        for (int i = 2; i <= num; i++)
        {
            fact = fact * i;
        }

        return fact;
    }

    static void Main()
    {
        int result = 0;
        int number = 0;

        MyDel del = new MyDel(CalculateFactorial);

        Console.Write("Enter the number: ");
        number = int.Parse(Console.ReadLine());

        result = del(number);

        Console.WriteLine("Factorial of number {0} is: {1}",number,result);
    }
}

Output:

Enter the number: 5
Factorial of number 5 is: 120
Press any key to continue . . .

Explanation:

In the above program, we created a Sample class that contains two static methods CalculateFactorial() and Main().

The CalculateFactorial() method is used to calculate the factorial of the specified number. In the Main() method, we bind the CalculateFactorial() method with delegate del and then read the value of variable number and then called the method CalculateFactorial() using delegate and assign the returned result into variable result that will be printed on the console screen.

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

total answers (1)

C# program to demonstrate the example of generic d... >>
<< C# program to demonstrate the example of an array ...