IEnumerable Expression-Bodied Member C #

I have a get-only property in C # that returns IEnumerable . If this property will only ever be given once, then I could define my property as follows:

 public IEnumerable Derp { get { yield return new SomeObject(); } } 

But how can I do this with a C # 6 expression? The following approaches do NOT work:

 // These definitions do NOT work public IEnumerable Derp => yield return new SomeObject(); public IEnumerable Derp => yield new SomeObject(); 

CS0103 compiler return error: "In the current context, the name" yield "does not exist. Is the yield ing element a physique expression even possible in C # 6? How about in C # 7?

I know that an IEnumerable member that returns only once looks smelly, but I'm mostly just curious. I came across this situation while experimenting with the NUnit TestCaseSource API, trying to provide a method that gives only one test case. I could also see that this applies to Unity developers who want to define an expression method that will be called using StartCoroutine ().

In any case, in advance for your thoughts!

+5
source share
1 answer

Expressed functions / properties cannot have operators ... You cannot, for example:

 static int Test(int x) => if (x > 0) x else 0; 

or even

 static int Test(int x) => return x; 

yield is an expression ... you cannot use it :-)

Please note that you can:

 IEnumerable<SomeObject> Derp => new[] { new SomeObject() }; 

From the Roslyn github page , New Language Features in C # 6 :

2.1. The expression of bodies on elements similar to the Method Methods, as well as user-defined operators and transformations, can be given the body of an expression using the "lambda arrow":

The effect is exactly the same as if the methods had a block body with one return statement.

For void return methods — and tasks returning async methods — the arrow syntax still applies, but the expression following the arrow must be an operator expression (same as a rule for lambda):

So, there is an exception for void return methods, but still it only covers calling methods (you can => Console.WriteLine("Hello"); but you can't => if () ).

+10
source

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


All Articles