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

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

Answers


Your Select call is creating new instances of MyType, which means that...

When list is typed as IEnumerable<MyType> then you're dealing with a new sequence of new objects each time you enumerate list. The objects to which you're adding event handlers are not the same objects that you're subsequently testing.

When list is typed as MyType[] (by using the ToArray call) then you're dealing with the same collection of objects each time you enumerate list. The objects to which you're adding event handlers are the same objects that you're subsequently testing.


Need Your Help

How to create an Handle (not event handler) in VB6?

vba vb6

Is there a way to create an handle in VB6? Also, is there a way to listen on this handle via VB6?

SQL Server -- Is it possible to step through a stored procedure

asp.net sql-server-2005

I have a stored procedure being executed from an ASP.NET application. Is it possible to attach to the procedure and step through it using SQL Server 2005?