Sponsored Ad

Thursday, October 29, 2009

Lterator blocks in C# 2: auto-generated state machines

Iterators have been in .NET since its first release, but C# 2 made them easy to implement using iterator blocks. In this editorial I'll go in to details of how the Microsoft C# compiler converts iterator blocks in to state machines. If you are not sure about the IEnumerable & IEnumerator interfaces (& their generic counterparts) or the basics of iterator blocks, it would be worth reading an editorial giving more details about them before continuing with this editorial.Pretty much all of this editorial is implementation-specific. The Mono compiler may approach things in a slightly different way, for instance. It is likely to be similar though; when in doubt as to what you can rely on, consult the language specification.

what's the pattern?

This article originally was because a reader asked about the difference between the use of repeater blocks for methods returning IEnumerator IEnumerable and returning. Moreover, there is a choice between non-generic interfaces and generic. Let's start by using the same iterator block for each of the four possibilities, and seeing the differences in the generated code. Throughout this article I will present the equivalent C # code that the compiler produces. Obviously, the compiler does not actually produce C #, but I've used reflector to decompile the code as C #.

Sample first Tour will only give the numbers 0 through 9 in sequence. Initially we will declare the method to return the nongeneric IEnumerator. Here is the complete code:

using System;
using System.Collections;

class Test
{
static IEnumerator GetCounter()
{
for (int count = 0; count < 10; count++)
{
yield return count;
}
}
}

Simple, right? Well, let's see what becomes after compilation. Hold your breath ...

State management

There are up to x pieces of state that the iterator type needs to keep track of:v

  • Your "virtual instruction pointer" (ie, when it comes)
  • Local variables
  • The initial parameter values, and this
  • The thread of creation (as shown above, and only in the case of IEnumerable, I will cover this more)
  • The last value given (ie current, which is trivial, not enough to warrant separate attention)

We'll look at each of the first three in turn

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers