Psychic Debugging, Part Two

A number of readers have the mysterious fifth sense which gives them the ability to deduce that the GetBars method from yesterday’s post contains a yield return and is therefore an iterator. Remember, as the standard states (in section 10.14.4):

[…] execution of the code in the iterator block occurs when the enumerator object’s MoveNext method is invoked.

Since the test program does not invoke MoveNext, the check for null is never executed, and therefore the exception is never thrown.

Since most of the interesting new sequence operators available in C# 3.0 are implemented with iterators it probably will be increasingly important for developers to understand a bit more about how iterators work behind the scenes. I may do some blog posts on that over the next little while.

Comments (6)

  1. Yes, please do go into that. Especially how they interact with variable capture and so on. It’s not too hard to be a bit careless and accidentally return an iterator that only works once, for instance.

  2. Alex James says:


    I understand the point you are making…

    but correct me if I am wrong but there is absolutely no guarantee that the method is using yields at all…


       static public IEnumerable<Bar> GetBars(Foo foo) {

           if (foo == null)

               throw new ArgumentNullException("foo");

           return SomeOtherClass.GetBars(foo);

    I which case that means that the ArgumentNullException will get fired?


  3. EricLippert says:


  4. Dean Harding says:

    It’d probably be a good idea to do your parameter validation in a helper method that calls the "real" GetBars(). That way, you get the exception ASAP, rather than the first time you call MoveNext…

  5. Mona says:

    I am working with VB.NET, I have many mathematical equations in my windows application, which differ according to many options I selected from previous form. So I m using thesse equation as strings in database and according to the selected options from the previous form it drag the its equation, which I concatinate to a variable (number) according to the selected age. So this equation doesn’t work because it defined as nvchar in the databse and the variable is number, I tried the function eval() which I use in asp to solve this but it didn’t work. I want to know if there is a function in VB.NET can solve this problem or what can I do to solve it.

  6. Iterator blocks have an interesting property: they defer execution. When the method (or property) is