Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
335 views
Welcome To Ask or Share your Answers For Others

1 Answer

The expression-bodied syntax is really only a shorter syntax for properties and (named) methods and has no special meaning. In particular, it has nothing to do with lambda expressions.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...