I wrote before about cool uses of anonymous methods (sometimes called anonymous delegates). Finding uses for generics is also a no-brainer – as a minimum, you’ll use generics with the generic collections.
But the iterators, supported through the new yield keyword, are slightly more tricky. It is easy to write a trivial example on how to create them yet it’s another thing to make a compelling case.
However, I found a case where it’s almost always applicable. Assume you have a class B somewhere in your code and that this class contains a collection of items of class C. Something like this:
class B
{
private List<C> _coll;
internal IEnumerable<C> GetAllCsThatSatisfySomeCondition()
{
foreach(C c in _coll)
{
if(/* complicated criteria */)
yield return c;
else if (/* extra exit criteria */)
break;
}
yield break;
}
}
Now you can use this from some class A like this:
foreach(C c in _b.GetAllCsThatSatisfySomeCondition())
{ /* do something with the C's... */ }
The elegance in this is that you are not exposing the way C’s are stored in B, nor the complicated criteria by which they are taken out. Think about the alternative – you’d have to expose elements of _coll somehow (maybe through a custom indexer) and to reason about iteration directly in the last foreach loop. Not nice, especially if this code is supposed to be called from many places, which would either lead to duplication or the awkward placement of the wrapper method (where would you put it?).
I am so glad I can base my product on the CLR 2.0 and not 1.1.
P.S. I am shocked to find that Java got the foreach equivalent only in the latest (1.5) revision. WTF?
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5