The rise of the lambda "goes-to" operator => has seen a surge in a variety of languages and now C# 6.0 allows methods, operators, read-only properties and read-only indexers to be defined with this syntax instead of the traditional {} block.
Code
csharp
// Read-only property
public string FullName => FirstName + " " + LastName;
// Takes and returns a value
public string GetPostExcerpt(Post p)
=> string.Join(' ', p.Body.Split(' ').Take(25)) + " ...";
// No return type
public void StartCache() => cache.Start(this, cachePolicy);csharp
// Read-only property
public string FullName
{
get { return FirstName + " " + LastName; }
}
// Takes and returns a value
public string GetPostExcerpt(Post p)
{
return string.Join(' ', p.Body.Split(' ').Take(25)) + " ...";
}
// No return type
public void StartCache()
{
cache.Start(this, cachePolicy);
}Notes
- The body must be a single expression, and for members with a return type its value is returned without needing
return - Support was extended to constructors, finalizers and
get/setaccessors with Expanded expression bodied members C# 7.0 - Unlike Lambda expressions C# 3.0 there is no block-bodied form, use a normal
{}body when you need multiple statements