C# 2.0 Iterators

As you may have noticed in the example, the iterator design pattern isn't overly difficult to implement. However, those of you who have read many of my prior articles know that I'm all about eliminating unnecessary code and performance overhead. Hence, the prior implementation has both unnecessary code and performance overhead. If the implementation involves value types, boxing and unboxing get involved, which leads to the performance overhead. The unnecessary code results from the iterator needing in-depth knowledge of the aggregate class. With C# 2.0, you can rely on generics and the compiler to help reduce the amount of code and performance impact. A new yield statement appears only inside an iterator block. Each call to GetEnumerator will yield the next value in the collection, and all of the state management is handled.

C# 2.0 Iterator Implementation Sample Code

The following sample code removes the nested class from the previous example. It replaced the entire GetEnumerator method to use the yield statement. Additionally, it includes the use of generics so you can apply the example to any type:

There is less code involved in the overall solution and the performance is improved.

Future Columns

The topic of the next column has yet to be determined. If you have something in particular that you would like to see explained, please e-mail me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer (MCSD, MCSE, MCDBA) is a senior architect of .NET applications for large and mid-sized organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the second year in a row. You can reach Mark at mstrawmyer@crowechizek.com.