27

C# 6 introduces expression-bodied members, which allow for simplified code in methods and properties that only return the result of an expression:

public override string ToString()
{
     return string.Format("{0} {1}", _field1, _field2);
}

becomes:

public override string ToString() =>
    string.Format("{0} {1}", _field1, _field2);

Since we now have two exactly equivalent and valid syntaxes, some rule of thumb must be used to decide which to use. When is the new alternative appropriate?

Asik
  • 864
  • 8
    Umm, when the body of the member is an expression? – Jörg W Mittag Aug 24 '15 at 16:53
  • 2
    That would answer the question "when is it possible to use expression bodied members". – Asik Aug 24 '15 at 17:12
  • 7
    Not completely related, but can't you use public override string ToString() => $"{_field1} {_field2}";? – Thaoden Aug 24 '15 at 17:15
  • 3
    @JorgWMittag I'd add "... that doesn't have side effects" to that. Declaring a method in a functional style when it isn't purely functional would be misleading. – Jules Aug 25 '15 at 17:59

2 Answers2

25

From C#/.NET Little Wonders: Expression-Bodied Members in C# 6:

So, should you use this? It all comes down to style. My gut would be to limit this to simple expressions and statements that can clearly be understood at first glance.

(emphasis, mine; see Update 1 below)

More from the Summary of the article above:

So C# 6 now gives us the ability to specify get-only property and method bodies with expressions. This can help reduce the syntax burden of very simple methods to make your code more concise.

However, with all things, use your judgment on whether it fits for any given situation. When an expression is very long or complex, using the full body syntax may still be more readable.

And another quote about performance, because performance problems can also play into when it's appropriate to use a certain language feature:

Now, you may ask, does this have any performance implications at runtime? Actually, the answer is no. This is simply syntactical sugar that expands into the same IL as writing the full body. It does not create a delegate, it is simply borrowing the lambda expression syntax to simplify writing simple bodies that result in an expression.

(emphasis, the author)

Update 1: @JörgWMittag said

This makes no sense. "limit this to simple expressions and statements"? Huh? It doesn' even work with statements, only with expressions!

It appears the original author may have misspoke. To clarify, from The New and Improved C# 6.0:

Expression bodied functions are another syntax simplification in C# 6.0. These are functions with no statement body. Instead, you implement them with an expression following the function declaration.

To be clear, this doesn't make a method or property an Expression. It utilizes the Expression syntax to reduce the lines of code (and numbers of curly braces).

My original recommendation still stands: Use it when it makes your code obvious and easier to understand, not simply because you can use it.

Glorfindel
  • 3,137
  • 2
    This makes no sense. "limit this to simple expressions and statements"? Huh? It doesn' even work with statements, only with expressions! I'm also not convinced that adding clutter (two parentheses and a return keyword) can ever lead to more readability. After all, the complex expression is still the exact same complex expression, just buried in syntactic clutter. – Jörg W Mittag Aug 24 '15 at 21:00
  • 3
    From what I've read expression bodied members are not actually expressions. They are syntactic sugar. Unless the C# spec has changed since the blog post it does support methods with void return types. – Greg Burghardt Aug 24 '15 at 23:26
  • 1
    I could be wrong, but I believe that side effects are disallowed in Expression Statements. So to me, the benefit of expression statements is that you're telling the reader that this "expression" is pure and that there are no hidden side effects that you, the reader, need to look for. – John Apr 19 '17 at 17:56
  • 1
    @John "disallowed" is completly wrong. You can do all the shenanigans like creating an action, inside the actions declaration set member variables and then invoke the action. Hence, side effects are obviously not disallowed. I would definitely discourage them tho, they miss the point of the expression syntax. – Mafii May 26 '17 at 14:45
  • @Mafii. Thanks. I have since learned that you can do "expression statements", which was described as being "modern". To me, however, the very idea is just confusing. – John Jun 05 '17 at 17:29
15

Functional programming languages consist only of expressions, so most have had a feature like this from essentially the beginning. You use it when you have a relatively short, often frequently repeated, expression that can be replaced by an even shorter, much more meaningful name.

A common example would be predicates that are used elsewhere, like:

public static bool isOdd(int num) => (num % 2) == 1;

If the expression is too long, it's better to split it up into separate functions or perhaps one function with named intermediate results. If it's short, but you can't think of a good name, you're better off just copying the expression rather than creating a terrible name like condition1 or something.

AGB
  • 103
Karl Bielefeldt
  • 147,435