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?
quotient
orratio
would have saved a lot of head-scratching :p – Porringeryield
keyword in your example. In your example, "yield" is an identifier. – Margaretmargaretaint @yield
. I guess because it's not a contextual keyword unto itself. – Gilmagilman@yield
. Contextual keywords only function as keywords in a certain context. Non-contextual keywords likeclass
are always keywords in every context, and therefore need to have an @ sign prepended if you want to use them as identifiers. – Margaretmargareta