Home
VB.NET
Iterator Example: Yield Keyword
Updated Apr 14, 2022
Dot Net Perls
Iterator. An Iterator returns values when repeatedly called—it maintains state between calls. The Yield keyword returns a value from an Iterator. Control then resumes next after the Yield.
Implementation notes. In VB.NET, the Yield and Iterator keywords use code generation. Special classes are generated. In these classes, the state of Iterators are maintained.
An example. The ComputePower Function generates a series of numbers with an increasing exponent value. We pass, as arguments, 2 values—the base number and the highest exponent required.
Detail In ComputePower we iterate through the exponents. We compute the running total and store it in the local variables.
Detail With the Yield keyword we "yield" control of ComputePower to Main. When next called, we resume after Yield.
Module Module1 Sub Main() ' Loop over first 10 exponents. For Each value As Integer In ComputePower(2, 10) Console.WriteLine(value) Next End Sub Public Iterator Function ComputePower( ByVal number As Integer, ByVal exponent As Integer) As IEnumerable(Of Integer) Dim exponentNum As Integer = 0 Dim numberResult As Integer = 1 ' Yield all numbers with exponents up to the argument value. While exponentNum < exponent numberResult *= number exponentNum += 1 Yield numberResult End While End Function End Module
2 4 8 16 32 64 128 256 512 1024
For performance, a simple For-loop or List is a better choice. Generate values, place into an array, and return. This avoids much of the excess classes that an Iterator will require.
For
List
Array
Important Iterators are not low-level features. They use keywords and short syntax, but a significant amount of code is generated.
Summary. The Iterator and Yield features in VB.NET are advanced—complex code is generated. We often call Iterators within a For Each loop. Values can be returned based on any logic.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 14, 2022 (rewrite).
Home
Changes
© 2007-2025 Sam Allen