Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Caution when using yield return

5.00/5 (6 votes)
24 Jul 2014CPOL 11.1K  
Caution when using yield return

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 :

C++
        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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)