With C# 6's expression-bodied members, I can write:
public string FullName => $"{_firstName} {_lastName}";
And I can write:
static void Print(string message) => Console.WriteLine(message);
In the first instance, the expression returns something. In the second, it doesn't.
What's happening here for it to determine how to 'act' without the need for any additional syntax? Or is it simply a case of it looking at the method signature during compile time?
I'm not a big fan of leaving things to 'just work' without knowing what's happening.
First, FullName
is a property. It always returns a value. Hence, the signature of the body should be Func<T>
, where T
is the return type (which is defined as string
in your sample) or the equivalent delegate.
The signature of your method void Print(string message)
is Action<string>
, since the compiler understands that a void does not return a value and takes a single parameter. It understands some statements return a value (like => "a"
) and some can stand on their own (although they might return a value like => new object()
). Hence it can tell you if you mess up: "CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement".