Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between lambda expressions and anonymous methods - C# [duplicate]

Tags:

c#

.net

Duplicate: delegate keyword vs. lambda notation

I understand the anonymous methods can be used to define delegates and write inline functions. Is using Lambda expressions any different from this?

I guess I am a little confused on when to use what.

Edit: Also, appears that to use either anonymous or lambdas, there needs to be an Extension method for the type?

like image 633
Bob Smith Avatar asked Apr 17 '09 16:04

Bob Smith


People also ask

Is lambda expression and anonymous function?

Lambda Expression –A function without name is called anonymous function. For lambda expression we can say that it is anonymous function. Example: Kotlin.

Why is anonymous function called lambda?

In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

What are anonymous methods?

Anonymous method is a block of code, which is used as a parameter for the delegate. An anonymous method can be used anywhere. A delegate is used and is defined in line, without a method name with the optional parameters and a method body. The scope of the parameters of an anonymous method is the anonymous-method-block.

Does C# have anonymous functions?

Anonymous MethodAnonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type.


1 Answers

A lambda expression is simply shortcut syntax for an anonymous method. Anonymous methods look like this:

delegate(params) {method body}

The equivalent lambda expression would look like this:

params => method body

In short, all lambda expressions are anonymous methods, but it is possible to have an anonymous method that is not written in lambda syntax (like the first example above). Hope this is helpful!

like image 199
Adam Alexander Avatar answered Sep 27 '22 22:09

Adam Alexander