Why does an event handler never get called if it’s added within 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 list is assigned like
list = someCollection.Select(i => new MyType(i)).ToArray();
the event handler does get called..
Why? (I imagine it has something to do with the fact that a LINQ query is lazy, but the fact of looping through the result isn’t enough?)
Your
Selectcall is creating new instances ofMyType, which means that…When
listis typed asIEnumerable<MyType>then you’re dealing with a new sequence of new objects each time you enumeratelist. The objects to which you’re adding event handlers are not the same objects that you’re subsequently testing.When
listis typed asMyType[](by using theToArraycall) then you’re dealing with the same collection of objects each time you enumeratelist. The objects to which you’re adding event handlers are the same objects that you’re subsequently testing.