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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…