Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c# - Expression-bodied members vs Lambda expressions

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...