Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A local variable can be named as yield

Just found out

foreach (int yield in items) {
  yield return yield * 2;
}

or

int yield = 10; 

are valid codes in C#.

I can understand it could be easy for the compiler to differentiate between a variable yield and an iterator yield, but still it adds to the confusion and lessen the readability of the code.

Do we know the exact reasons why is it allowed?

like image 990
NileshChauhan Avatar asked Mar 22 '13 17:03

NileshChauhan


2 Answers

Do we know the exact reasons why is it allowed?

Yes. yield is only a contextual keyword. It was introduced in C# 2, and the team didn't want to break code which already used yield as an identifier.

The same is true for other contextual keywords which have been introduced since 1.0, such as partial. See Eric Lippert's blog post for the complete list.

but still it adds to the confusion and lessen the readability of the code

So don't do that then? There are any number of things you can do to make your code really, really hard to read. You could make all your variable names just underscores:

private int _;
private string __;
// etc

Do you do that? If not, why would you expect people to write confusing code with yield specifically?

like image 64
Jon Skeet Avatar answered Nov 11 '22 23:11

Jon Skeet


yield is a contextual keyword. It could be an ordinary keyword, but they chose to make it a contextual keyword.

The main reason for contextual keywords is backwards compatibility. If they added a normal keyword to the language, it might break code that is being copied from older versions of the language.

For example, imagine compiling this code after yield was added as a normal keyword:

bool yield = false;
// bla bla

It wouldn't work very well, would it? You'd have to rename your variables before you could compile it with the newer version.

like image 2
Kendall Frey Avatar answered Nov 11 '22 22:11

Kendall Frey