less than 1 minute read

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

Expression-bodied methods make it possible for methods and properties to be used as expressions instead of statement blocks, just like lambda functions.

Let’s revisit the Person.ToString method in the Awesome string formatting blog post.

public class Person
{
  public string Name { get; set; }

  public Address HomeAddress { get; set; }

  public override string ToString()
  {
    return string.Format("{Name} lives in {HomeAddress?.City ?? "City unknown"}.");
  }
}

The ToString method can be written as a lambda function.

public override string ToString() => string.Format("{Name} lives in {HomeAddress?.City ?? "City unknown"}.");

And simplified with String interpolation.

public override string ToString() => $"{Name} lives in {HomeAddress?.City ?? "City unknown"}.

Use expression-bodied methods anywhere…

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
public static Complex operator +(Complex a, Complex b) => a.Add(b);
public static implicit operator string (Person p) => "{p.First} {p.Last}";

Tags: ,

Categories:

Updated:

Comments