The yield
keyword documentation says:
The yield keyword signals to the compiler that the method in which it appears is an iterator block.
I have encountered code using the yield
keyword outside any iterator block. Should this be considered as a programing mistake or is it just fine?
EDIT Sorry forgot to post my code:
int yield = previousVal/actualVal;
return yield; // Should this be allowed!!!???
Thanks.
The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it.
You can access the EvenNumbers static property to display the even numbers between 1 and 10 at the console window using the code snippet given below. You can use the "yield break" statement within an iterator when there are no more values to be returned. The "yield break" statement is used to terminate the enumeration.
The yield keyword is use to do custom stateful iteration over a collection. The yield keyword tells the compiler that the method in which it appears is an iterator block. yield return <expression>; yield break; The yield return statement returns one element at a time.
It's okay to use yield
outside an iterator block - it just means it isn't being used as a contextual keyword.
For example:
// No idea whether this is financially correct, but imagine it is :)
decimal yield = amountReturned / amountInvested;
At that point it's not a contextual keyword (it's never a "full" keyword), it's just an identifier. Unless it's clearly the best choice in terms of normal clarity, I'd try to avoid using it anyway, but sometimes it might be.
You can only use it as a contextual keyword for yield return
and yield break
, which are only ever valid in an iterator block. (They're what turn a method into an iterator.)
EDIT: To answer your "should this be allowed" question... yes, it should. Otherwise all the existing C# 1 code which used yield
as an identifier would have become invalid when C# 2 was released. It should be used with care, and the C# team have made sure it's never actually ambiguous, but it makes sense for it to be valid.
The same goes for many other contextual keywords - "from", "select", "where" etc. Would you want to prevent those from ever being identifiers?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With