[ACCEPTED]-yield return versus return select-yield

Accepted answer
Score: 17

The yield return technique causes the C# compiler to 9 generate an enumerator class "behind the 8 scenes", while the Select call uses a standard 7 enumerator class parameterized with a delegate. In 6 practice, there shouldn't be a whole lot 5 of difference between the two, other than 4 possibly an extra call frame in the Select case, for 3 the delegate.

For what it's worth, wrapping 2 a lambda around DoSomething is sort of pointless as 1 well; just pass a delegate for it directly.

Score: 12

In the slow-moving corporate world where 5 I currently spend more time than I'd wish, yield 4 return has the enormous advantage that it 3 doesn't need that brand new .NET 3.5 Framework 2 that won't be installed for at least another 1 2 years.

Score: 4

Select only allows you to return one object 16 for each item in your "items" collection. Using 15 an additional .Where(x => DoIReallyWantThis(x)) allows you to weed out unwanted 14 items, but still only allows you to return 13 one object per item. If you want potentially 12 more than one object per item, you can use 11 .SelectMany but it is easy to wind up with a single 10 long line that is less than easy to read.

"yield 9 return" has the potential to make your code 8 more readable if you are looking through 7 a complex data structure and picking out 6 bits of information here and there. The 5 best example of this that I have seen was 4 where there were around a dozen separate 3 conditions which would result in a returned 2 object, and in each case the returned object 1 was constructed differently.

More Related questions