Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / C++
Tip/Trick

Caution when using "yield return"

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
24 Jul 2014CPOL 10.6K   2
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)


Written By
Web Developer
Korea (Republic of) Korea (Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionResharper for your help Pin
Carlos190728-Jul-14 1:23
professionalCarlos190728-Jul-14 1:23 
GeneralMy vote of 5 Pin
Antonio Nakić Alfirević24-Jul-14 23:10
Antonio Nakić Alfirević24-Jul-14 23:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.