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#?
Submitted by Nidhi, on September 15, 2020

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.


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);


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


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 »


What's New (MCQs)

Comments and Discussions!

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.