Consider the following expression:
public override string ToString() => "ABCDEFG";
compiles to this:
public override string ToString()
{
return "ABCDEFG";
}
despite this syntax being syntactic sugar, I would have expected ToString()
to equate to Func<string>
Func<string> ToString = () => { return "ABCDEFG"; };
Notice that Func<string>
requires a return
statement, but the lambda syntax for the ToString()
override does not.
Why does Lambda syntax for overrides not require the use of return
?
Firstly, it's not a lambda expression - it's just that expression-bodied members (introduced in C# 6) also use the syntax of =>
. They don't involve creating a delegate instance or an expression tree though.
As for why return
isn't needed - it isn't needed in lambda expressions either, when they're expression-bodied lambda expressions:
Func<string> toString = () => "ABCDEFG";
That's been true ever since lambda expressions were introduced in C# 3, and is by far the most common case in LINQ, e.g.
var query = strings.Where(x => x.Length > 3)
.Select(x => x.ToUpperInvariant());
See more on this question at Stackoverflow