views:

86

answers:

1

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?

+5  A: 

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.

Mehrdad Afshari
Thanks man. I quickly checked the place where the IEnumarable was created and this what I foundfrom rec in recs select new XYZ(rec)Thanks again for ur help.
malay