Understanding Lambda expressions and delegates

Viewed 28386

I have been trying to figure this out for quite sometime (reading online blogs and articlaes), but so far unsuccessful.

What are delegates? What are Lambda Expressions? Advantages and disadvantages of both? Possible best practice of when to use one or the other?

Thanks in advance.

6 Answers

There is one important difference is there where we can use lamda than delegate.

private delegate int emptymethoddel();
// Delegate for method with no params and returns int

The equivalent framework delegate type is: Func<int>

But you cannot create new delegate instance/func from parameterized method.

private int TwoArgMethod(int i, int j)
{
    return i + j;
}

but, with lambda, you can get delegate for the above method.

Func<int> retmethod = () => TwoArgMethod(10, 20);

but for delegate instantiation, we cannot do as below

emptymethoddel retmethod4 = new emptymethoddel(TwoArgMethod(10,20)); 
// mismatch method signature

With lambda, we can get pointers to methods that doesn't match "Func" or any other variants.

Related