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.
It's okay to use
yield
outside an iterator block - it just means it isn't being used as a contextual keyword.For example:
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
andyield 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?