tags:

views:

89

answers:

4

I do something like this and the value in the collection doesn't change

                [Test]
                public void EnumerableTest()
                {
                    var source = GetFoos();

                    source.First().One = "hello";

                    Assert.AreEqual(source.First().One, "hello");
    //it fails

                }

//I actually return this from a repository
                public IEnumerable<Foo> GetFoos()
                {
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                }
+6  A: 

That is because you create new instances each time you enumerate over GetFoos.

norheim.se
@norheim.se and how would you fix this ?
Omu
store them out of the scope of the function?
PoweRoy
@omu I would either go for fearofawhackplanet's solution, or your accepted answer.
norheim.se
+2  A: 

If you change the var source = GetFoos(); into var source = GetFoos().ToList();, the list is read immediately (and in full). Then you should be able to change the values.

Don't forget to store the changed values or else they revert the next time you read them.

Hans Kesting
+1  A: 

It is because of your use of yield return.

You could write instead:

public IEnumerable<Foo> GetFoos()
{
    return new List<Foo>
    {
        new Foo { One = "1", Two = "2", Three = true },
        new Foo { One = "1", Two = "2", Three = true },
        new Foo { One = "1", Two = "2", Three = true },
    };
}
fearofawhackplanet
+1  A: 

When you call First() a new Enumerator is created. So GetFoos() is called again and return a new object.

Itay