Expression Bodied Members are a shorter syntax for writing a method if it only contains a single expression. The syntax uses the =>
operator instead of curly braces ({ }
) much like a Lambda Expression used in an Inline Delegate. If the method returns a value, the return
keyword is not necessary. For example, the following regular method:
public string GetFullName()
{
return firstName + " " + lastName;
}
Could be written as a single line:
public string GetFullName() { return firstName + " " + lastName; }
Which can be shortened a bit using an expression body:
public string GetFullName() => firstName + " " + lastName;
Read-Only Properties can also have expression bodies, which is particularly useful for providing a public accessor for a non-public Serialized Field, for example:
// Private serialized field.
[SerializeField]
private AnimancerComponent _Animancer;
// Public accessor so that other types can get the value but not set it.
public AnimancerComponent Animancer => _Animancer;