Introduction
When we use "yield return", be careful!
Background
Understanding "yield return" statement.
Using the code
When we make collection, yield return is very helpful.
For example, if we use yield return, we don't need to make some buffer array like this :
IEnumerable<TestObject> GetObjects()
{
for (int i = 0; i < 10; i++)
{
yield return new TestObject() { Value = i };
}
}
And we can write consuming code of return value from yield return method.
var objects = GetObjects();
foreach (var item in objects)
{
item.Value += 10;
}
foreach (var item in objects)
{
Debug.Print(item.Value.ToString());
}
We may expect it will print 10 to 19 because of adding 10. But it will display 0 to 9.
"TestObject" will be created when called not at GetObjects() but at the foreach statement.
So TestObject will be created two times at each foreach statement.
So the item in first foreach statement is different from the item in second foreach statement.
For solving the problem, you may use like ToArray() when calling GetObjects like this :
var objects = GetObjects().ToArray();
In this case, TestObject will be created only one time when called ToArray().
Thanks.
Points of Interest
Operation of yield return.
History
Initial release.