C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Why return a List<T> from GetSampleProducts?

Chapter 1: The changing face of C# development: 1.1.2

Created: 1/22/2008
Last updated: 1/22/2008

The GetSampleProducts method in the C# 2 and 3 version of the Product class demonstrates the feature of generics, and collection initializers in C# 3 - but it could do more.

Suppose we'd declared it to return IEnumerable<Product> instead of List<Product>. Then we could have seen iterator blocks with yield return statements. Another major language feature mentioned in the first chapter... So why didn't I do it?

There are two reasons. The first, being totally honest, is that I didn't think of it. It was only when Eric mentioned it at tech review that I saw the possibilities. However, leaving aside the size of change it would have required late on in the editing process, I still don't think it would have been a good idea - simply because iterator blocks scare me slightly. Closures are a bit mind-bending but basically make sense - iterator blocks are a whole extra level of magic.

Don't get me wrong, I love them and use them - but I think that presenting readers with that level of compiler magic that early in the book might be a little off-putting. As soon as you start thinking about the way that at execution time you start dipping into bits of your method at a time, it all gets somewhat bizarre.

Oh, and on a minor point - if the method hadn't returned a List<Product>, it would have been slightly harder to demonstrate sorting in C# 2 :)