How do expressing bodies distinguish between void and non-void?

With C # 6 expressive members, I can write:

public string FullName => $"{_firstName} {_lastName}";

And I can write:

static void Print(string message) => Console.WriteLine(message);

In the first case, the expression returns something. In the second - no.

What happens here to determine how to "act" without the need for any additional syntax? Or is it just the case when he looks at the signature of a method at compile time?

I am not a big fan of leaving things β€œjust working” without knowing what is going on.

+5
source share
1 answer

First, FullName is a property. It always returns a value. Therefore, the body signature must be Func<T> , where T is the return type (which is defined as string in your example) or the equivalent delegate.

The signature of your void Print(string message) method is Action<string> , because the compiler understands that void does not return a value and takes one parameter. He understands that some operators return a value (for example, => "a" ), and some can stand on their own (although they can return a value like => new object() ). Therefore, you can say whether you are spoiled: "CS0201: only assignment, call, increment, decrement and new object expressions can be used as an operator."

+3
source

Source: https://habr.com/ru/post/1243296/


All Articles