Home »
.Net »
C# Programs
C# program to return the value from the method using a delegate
Here, we are going to learn how to return the value from the method using a delegate in C#?
By Nidhi Last updated : April 03, 2023
Returning value from method using a delegate
Here, we will create a static method CalculateFactorial() that will return the result, here we bind the method with delegate and return the resulted value using a delegate.
C# code to return the value from the method using a delegate
The source code to solve this program 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.
C# Delegate Programs »