A lambda expression is a block of code (an expression or a statement block) that is treated as an object. It can be passed as an argument to methods, and it can also be returned by method calls.
(input parameters) => expression
SomeFunction(x => x * x);
Looking this statement I was wondering what's the difference when using lambdas and when using Expression-bodied?
public string Name => First + " " + Last;
The expression-bodied syntax is really only a shorter syntax for properties and (named) methods and has no special meaning.
These two lines are totally equivalent:
public string Name => First + " " + Last;
public string Name { get { return First + " " + Last; } }
You can also write expression-bodied methods (note the difference to your lambda expression doing the same. Here you specify a return type and a name):
public int Square (int x) => x * x;
instead of
public int Square (int x)
{
return x * x;
}
You can also use it to write getters and setters
private string _name;
public Name
{
get => _name;
set => _name = value;
}
and for constructors (assuming a class named Person
):
public Person(string name) => _name = name;
Using the tuple syntax, you can even assign several parameters
public Person(string first, string last) => (_first, _last) = (first, last);
This works for assigning to properties as well.
Expression bodied methods are syntactic sugar. Instead of writing this:
public string GetName()
{
return First + " " + Last;
}
you can just write this:
public string GetName() => First + " " + Last;
and the result of calling either the first or the second would be exactly the same.
The same is true also for all the kinds of expression body members.
On the other hand, a lambda expressions as it is stated formally here is:
an anonymous function that you can use to
create delegates or expression tree types.
That being said it is clear that despite the similarity in syntax, there are two completely different things.