Using expression-bodied members allows you to define the body of a method or property as a single expression without a return keyword (should it return something).
For example it turns these
int Method1()
{
return 5;
}
void Method2()
{
Console.WriteLine();
}
into these
int Method1() => 5;
void Method2() => Console.WriteLine();
A difference comes into play when you throw an exception from the body:
void Method3()
{
throw new Exception();
}
However, the following will not compile:
void Method3() => throw new Exception();
with the following messages:
Warning The member 'Program.Exception()' does not hide an inherited member. The new keyword is not required.
Error 'Program.Exception()' must declare a body because it is not marked abstract, extern, or partial
Error ; expected
Error Invalid token 'throw' in class, struct, or interface member declaration
Error Method must have a return type
Error Invalid expression term 'throw'
Why?
This feature is coming in C#7. From https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
Edit:
Updating this question to add links to newer info around how
throw
can now be used as an expression in expression-bodied members, ternary expressions and null-coalescing expressions, now that C# 7 is released:What's new in C# 7 - Throw expressions.
New Features in C# 7.0.
As Jeroen Vannevel explained, we can only use expressions for expression bodied members. I would not recommend this, but you can always encapsulate your (complex) code in an expression by writing a lambda expression casting it to an appropriate type and Invoke it.
This way you can still throw an exception in one line in an expression bodied member!
Probably there are good reasons not to do this. But I think that it is a design flaw that expression bodied members are restricted to expressions like this and can be worked around like in this example.
This happens because the first two code snippets (
5
andConsole.WriteLine
) are expressions. More specifically these are respectivelyNumericLiteralExpression
andInvocationExpression
.The latter one (
throw new Exception()
) is a statement -- in this case:ThrowStatement
.If you look at the Roslyn SDK you'll notice that a
MethodDeclarationSyntax
object has a propertyExpressionBody
of typeArrowExpressionClauseSyntax
which in turn has a property of typeExpressionSyntax
. This should make it obvious that only expressions are accepted in an expression-bodied member.If you look at the last code sample, you'll notice that it consists of a
ThrowStatementSyntax
which has in turn anExpressionSyntax
property. In our case we're filling that with anObjectCreationExpressionSyntax
object.What's the difference between an expression and a statement?
Why doesn't it accept statements as well?
I can only guess here but I would assume it's because that would open up way too many side-effects just to be able to throw an exception. I don't believe an expression and a statement have a common ancestor in the inheritance so there'd be a lot of code duplication. In the end I assume it boiled down to simply not worth being the hassle, even though it makes sense in a way.
When you write a simple expression as part of a method body that gets in fact wrapped under a
ExpressionStatementSyntax
-- yes, both combined! This allows it to be grouped together with other statements under theBody
property of the method. Under the hood, they must be unrolling this and extracting the expression from it. This in turn can be used for the expression-bodied member because at this point you're left with just an expression and no longer a statement.One important note here however is the fact that a return statement is.. a statement. More specifically a
ReturnStatementSyntax
. They must have handled this explicitly and applied compiler magic though that does beg the question: why not do the same forThrowStatementSyntax
?Consider the following scenario: suddenly,
throw
statements are accepted as well. However since an expression-bodied member can only have expressions as its body (duh) that means you have to omit thethrow
keyword and instead are left withnew Exception()
. How are you going to distinguish between intending areturn
statement and athrow
statement?There would be no difference between the expression-bodied variation of these two methods:
Both a
throw
and areturn
statement are valid method-endings. However when you omit them there is nothing that distinguishes the two -- ergo: you would never know whether to return or to throw that newly created exception object.What should I take away from this?
An expression-bodied member is exactly as the name says it is: a member with only an expression in its body. This means that you have to be aware of what exactly constitutes an expression. Just because it's one "statement" doesn't make it an expression.
Although its a old thread, but C# now supports throw expressions which were added in C# 7.
Previously,
No more. Now, as Null coalescing operator:
As Conditional Operator:
It is also possible in the Conditional Operator as well.
Expression bodied member:
Not an answer about why but a workaround: