How do expression bodied members distinguish between void and non-void?
Asked Answered
H

1

6

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.

Hierophant answered 18/2, 2016 at 9:20 Comment(7)
I think $"..." is just a short version of String.Format(...) which undoubtfully returns a string.Cauley
It is, it's another C# 6 feature called string interpolation. Maybe I've muddied the waters by using that as a test snippet. My question is more about how the expression syntax decides what to return and when.Hierophant
In your second example the return-type is void, isn´t it? There is no further compiler-decision on this. I don´t see your problem.Cauley
First one is a property, second one a method (I'm probably not getting the question aren't I? :p)Dolley
@AlexanderDerck And what if method returns a string instead of void? This has nothing to do with the actual inferred type.Cauley
@HimBromBeere - correct. If we were to 'manually' write the statement block, we would then omit the return keyword. So the compiler appears to have made that decision.Hierophant
@HimBromBeere static string Print(string message) => message; ? This is just another way of writing Action<T> and Func<T>Dolley
G
4

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".

Grosberg answered 18/2, 2016 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.