Skip Navigation Links

 CodeMatrixThe ultimate site for .NET programmers

Skip Navigation Links.    

Delegates and Lambda Expressions in C# 3.0

Lambda expressions are functions with a different syntax that enables them to be used in an expression context instead of the usual object-oriented method of being a member of a class. With a single syntax, we can express a method definition, declaration, and the invocation of delegate to execute it, just an anonymous methods can, but with a more terse syntax.

A projection is a lambda expression that translates on type into another.

A lambda expreesion looks like this:
j => j*50

The following code snippets demonstrates the importance of lambda expressions. It would help us understand how can one implement code in C# 1.0/2.0 without lambda expressions.

C# 1.0 way of implementation

public delegate int IncreaseByANumber(int j);
static public int MultiplyByANumber(int j)
{
    return j * 50;
}
public static void InvokeCSharp1_0()
{
    IncreaseByANumber increase =
        new IncreaseByANumber(MultiplyByANumber);
    Console.WriteLine("Result from C# 1.0 way of implementation= " + increase(20));
}
C# 2.0 way of implementation

public delegate int IncreaseByANumber(int j);
public static void InvokeCSharp2_0()
{
    IncreaseByANumber increase =
        new IncreaseByANumber(
            delegate(int j)
            {
                return j * 50;
            }
        );
    Console.WriteLine("Result from C# 2.0 way of implementation= " + increase(20));
}
C# 3.0 way of implementation

public delegate int IncreaseByANumber(int j);
public static void InvokeCSharp3_0()
{
    IncreaseByANumber increase = j => j * 50;
    Console.WriteLine("Result from C# 3.0 way of implementation= " + increase(20));
}


Downloads

The sample code can be downloaded from below link. The code is complied with Microsoft Visual C# 2008.




Copyright © 2008 www.codematrix.net, All Rights Reserved. Disclaimer