Friday, July 16, 2010

Nested function/subroutine in C#



This is how we simulate nested function in C# :

class Program
{
    static double Foo(double a, double b)
    {
        Func<double, double> Square = delegate(double z)
        {
            return z * z;
        };

        return Square(a) + Square(b);
    }

    static void Main(string[] args)
    {
        Console.WriteLine("{0}", Foo(3, 4));
        Console.ReadLine();
    }
}
// outputs 25

The first double in Func<double, double> is the parameter, the last double is the return type

The nested function capability in C# is just a lambda, so we can shorten the code to:

static double Foo(double a, double b)
{
    Func<double, double> Square = z => z * z;

    return Square(a) + Square(b);
}

No comments:

Post a Comment