Tuesday, May 15, 2012

Calculating Factorial using old school & Func Delegate

Hi, I am going to show 2 different implementation of calculating Factorial, first  by using old school format and then using Func delegates.
Important thing to note that using while using Func Delegate, its tricky as you can not define a recursive function using Func, so  what you do is you define a function variable and use that variable to perform recursion as shown in code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace TestConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine("Using old school factorial method:" + Factorial(number));
            var f = FactorialUsingFunc();
            Console.WriteLine("Using Func Delegate method :" +f(number));
            Console.ReadLine();
        }
 
        private static int Factorial(int n)
        {
            return (n > 1) ? n*Factorial(n - 1) : n;
        }
 
        static Func<intint> FactorialUsingFunc()
        {
            Func<intint> factorial = null;
            factorial = n => n < 1 ? 1 : n * factorial(n - 1);
            return factorial;
        }
 
    }
}

No comments:

Post a Comment