Does a foreach loop copy each item of an IEnumerable while iterating?
I have a foreach
loop like below
foreach (XYZ split in this.splits )
{
// this code is inserted for debug purpose only
bool check = object.ReferenceEquals(splits.First(), split);
.....
}
When I have single element in this.splits
, check is returning 开发者_如何学运维false. I have checked by some other way, check is always returning false. Any idea why this is happening?
Depends on the way the enumerator is implemented. The implementation is free to return a copy or the object itself. In fact, it can return whatever it likes; for instance, Enumerable.Range
returns a sequence of numbers and none of the elements are actually stored anywhere. They are generated on the fly. If the return type is a value-type, it's certainly a copy of something.
Also, nothing requires the object to return the same sequence each time GetEnumerator
is called on it. In your code example, it does it once in foreach
and another time when you call .First
. These sequences are not required to be equivalent.
精彩评论