Monday, July 12, 2010

Lambda Expressions

=> is pronounced goes to, that means that x => x * 2 should be explained as x goes to x * 2

A simple example multiplying two numbers

delegate int mul(int a, int b);
static void Main(string[] args)
{
    mul m = (x,y) => x * y;
    Console.WriteLine(m(5,5)); // 25
}

Simple example just comparing contents

delegate bool equ(int a, int b);
static void Main(string[] args)
{
    equ e = (x,y) => x == y;
    Console.WriteLine(m(5,5)); // True
    Console.WriteLine(m(5,4)); // False
}

Alternatively as Func<T, TResult> (notice not declaring the delegate)

static void Main(string[] args)
{
    Func<int, int, int> mul = (x,y) => x * y;
    Func<int, int, bool> equ = (x,y) => x == y;
    Console.WriteLine(m(5,5)); // 25
    Console.WriteLine(m(5,5)); // True
    Console.WriteLine(m(5,4)); // False
}

No comments:

Post a Comment