What happens when ToArray() is called on IEnumerable ?
Posted
by
Sir Psycho
on Stack Overflow
See other posts from Stack Overflow
or by Sir Psycho
Published on 2011-01-10T01:35:55Z
Indexed on
2011/01/10
2:53 UTC
Read the original article
Hit count: 184
c#
I'm having trouble understanding what happens when a ToArray() is called on an IEnumerable. I've always assumed that only the references are copied.
I would expect the output here to be: true true
But instead I get true false
What is going on here?
class One {
public bool Foo { get; set; }
}
class Two
{
public bool Foo { get; set; }
}
void Main()
{
var collection1 = new[] { new One(), new One() };
IEnumerable<Two> stuff = Convert(collection1);
var firstOne = stuff.First();
firstOne.Foo = true;
Console.WriteLine (firstOne.Foo);
var array = stuff.ToArray();
Console.WriteLine (array[0].Foo);
}
IEnumerable<Two> Convert(IEnumerable<One> col1) {
return
from c in col1
select new Two() {
Foo = c.Foo
};
}
© Stack Overflow or respective owner