Alex Rivera | Logout

What is the difference between lambdas and delegates in the .NET Framework?

Asked 2008-09-16T14:55:05.500
118

I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.

Edit
Report

3 Answers

29

One difference is that an anonymous delegate can omit parameters while a lambda must match the exact signature. Given:

public delegate string TestDelegate(int i);

public void Test(TestDelegate d)
{}

you can call it in the following four ways (note that the second line has an anonymous delegate that does not have any parameters):

Test(delegate(int i) { return String.Empty; });
Test(delegate { return String.Empty; });
Test(i => String.Empty);
Test(D);

private string D(int i)
{
    return String.Empty;
}

You cannot pass in a lambda expression that has no parameters or a method that has no parameters. These are not allowed:

Test(() => String.Empty); //Not allowed, lambda must match signature
Test(D2); //Not allowed, method must match signature

private string D2()
{
    return String.Empty;
}
answered 2008-09-16T15:16:59.053
3

A delegate is always just basically a function pointer. A lambda can turn into a delegate, but it can also turn into a LINQ expression tree. For instance,

Func<int, int> f = x => x + 1;
Expression<Func<int, int>> exprTree = x => x + 1;

The first line produces a delegate, while the second produces an expression tree.

answered 2008-09-16T15:07:32.773
2

A delegate is a Queue of function pointers, invoking a delegate may invoke multiple methods. A lambda is essentially an anonymous method declaration which may be interpreted by the compiler differently, depending on what context it is used as.

You can get a delegate that points to the lambda expression as a method by casting it into a delegate, or if passing it in as a parameter to a method that expects a specific delegate type the compiler will cast it for you. Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate.

The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.

answered 2008-09-16T16:36:13.323

Your Answer