Expression bodies on properties and methods

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

Expression bodies let you use lambda-style expression declarations for methods and properties. So, instead of:

public int Add(int x, int y) { return x + y; }
public static Rectangle CreateSquare(int left, int top, int size) 
{
  return new Rectangle(left, top, size, size);
}

public string Address
{
  get { return City + ", " + State + "  " + Zip; }
}

You can instead write:

public int Add(int x, int y) => x + y;
public static Rectangle CreateSquare(int left, int top, int size)
     => new Rectangle(left, top, size, size);

public string Address2 => City + ", " + State + "  " + Zip;

Note that, for the property, you don’t have to explicitly specify “get” since it is implied — and you can’t have a “set”.

For methods, I think that this is probably a bad idea, and I would avoid using it — you otherwise end up with two completely different formats for doing something with very little compelling advantage.

For properties, I am slightly less bothered, since it is a lot more compact (and in general I think that more compact code for simple operations is easier to read), but if the logic becomes complex (as lambdas have a habit of doing) then I would probably revert back to the more explicit format.

By the way, you can also use this syntax for indexers:

public Shape this[int index] => myList[index];

 

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*