Lambda expression vs anonymous methods

28,220

Solution 1

Yes, lambda expressions are just very special anonymous methods.

However, there are some deep differences. Start with Eric Lippert's Lambda Expression vs. Anonymous Methods, Part One and continue to the rest of the series.

Solution 2

The only difference is the lambda can be easily cast to Expression<Func<void>>. The delegates are purely just methods/closures, but the lambda can also be broken down into an expression tree:

Expression<Func<int, int>> expr = x => x*2; // Expression tree
Func<int, int> fun = x => x*2;              // Function
delegate int MyDelegate(int x);             // Delegate
MyDelegate del = x => x*2;                  // Same as Function and Delegate
Share:
28,220

Related videos on Youtube

lojol
Author by

lojol

Updated on July 09, 2022

Comments

  • lojol
    lojol almost 2 years

    I would like to know what is the difference. Currently I am learning this stuff and it seems to me like these are just the same:

    delegate void X();
    
    X instanceOfX;
    
    instanceOfX = delegate() { code };
    
    instanceOfX = () => { code };
    

    Also if the lambda are newer, should I just use lambda and forget on anonymous methods?

    • Anthony Pegram
      Anthony Pegram about 13 years
      Think in terms of evolution of the language. In C# 1, we had delegates. In C# 2, they added anonymous methods. C# 3 added lambdas. Easier ways to accomplish similar tasks. For more on the evolution, I would encourage you to check out the book C# In Depth.
  • B Bulfin
    B Bulfin about 13 years
    So what's special about them?
  • lojol
    lojol about 13 years
    What is special about them<? thanks
  • Doctor Jones
    Doctor Jones about 13 years
    @recursive for a start, one MAJOR difference is that single line Lambdas can be assigned to an Expression tree whereas Anonymous methods cannot.
  • CodesInChaos
    CodesInChaos about 13 years
    Note that this is only possible for a subset of lamdas: Expression-lamdas but not statement lamdas.
  • Eric Lippert
    Eric Lippert about 13 years
    Note that "Delegate" is a terrible name for a delegate type because it will be easily confused with System.Delegate, its base class.
  • kelloti
    kelloti about 13 years
    I apologize. I'm still drinking coffee this morning and I honestly couldn't think of another name
  • BlaShadow
    BlaShadow almost 11 years
    I prefer anonymous method, I'm not always using linq otherwise I like use FindAll from List.