Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "yield keyword" useful outside of an iterator block? [closed]

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.

like image 688
GETah Avatar asked Nov 25 '11 20:11

GETah


People also ask

What is the yield keyword used for?

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.

When would you use the yield break statement?

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.

What is the use of yield keywords in C#?

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.


1 Answers

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?

like image 142
Jon Skeet Avatar answered Jan 01 '23 19:01

Jon Skeet