Why does an event handler never get called if it's added within a loop on an ienumerable?

Posted by André Carvalho on Stack Overflow See other posts from Stack Overflow or by André Carvalho
Published on 2010-03-17T12:58:20Z Indexed on 2010/03/17 16:01 UTC
Read the original article Hit count: 341

Filed under:
|

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?)

© Stack Overflow or respective owner

Related posts about .NET

Related posts about ienumerable