Why is an event handler never called if it is added in a loop on an ienumerable?

Why is an event handler never called if it is added in a loop on an ienumerable?

For instance:

IEnumerable<MyType> list = someCollection.Select(i => new MyType(i));

foreach (var item in list)
item.PropertyChanged += item_PropertyChanged; <-- this never gets called

Bu if the list is assigned as

list = someCollection.Select(i => new MyType(i)).ToArray();

event handler called.

Why? (I believe this is due to the fact that the LINQ query is lazy, but the fact of enumerating the result is not enough?)

+5
source share
1 answer

Your call Selectcreates new instances MyType, which means ...

When listintroduced as IEnumerable<MyType>, then you are dealing with a new sequence of new objects with each listing list. The objects to which you add event handlers are not the objects you subsequently test.

list MyType[] ( ToArray), list. , , , .

+3

All Articles