4

I have a method that returns an IEnumerable<T>. I call this method form two places, and in one of those places I do not do anything with the results.

It looks like the C# compiler removes the call to that method even if I decorate it with [MethodImpl(MethodImplOptions.NoOptimization)]. The code doesn't even enter the calling method. If I add .ToList() at the end, though, it is executed.

Is there a way to disable this optimization by the compiler/runtime? Looking at the ILDASM output, it looks like it's more of a runtime optimization because the call is there.

6
  • 2
    What does the method look like? If you use yield the resulting enumerable is evaluated lazily.
    – odyss-jii
    Oct 2, 2014 at 12:32
  • 2
    It sounds like the method is returning a lazy IEnumerable<T> using the yield keyword. Adding .ToList() forces the IEnumerable<T> to be buffered and the method to be executed. This is very much a feature, not a bug! Oct 2, 2014 at 12:33
  • I am in fact using a yield keyword. I agree it's a feature. I was just wondering if there's a way to "disable" it. Guess the best one is to not use lazy for this particular method? Oct 2, 2014 at 12:35
  • It is not an optimization. Disabling it would change the flow of execution.
    – odyss-jii
    Oct 2, 2014 at 12:37
  • If lazy evaluation results in unexpected behaviour then you probably shouldn't be using it. It sounds like you should buffer the results in a list/array before returning. Oct 2, 2014 at 12:37

1 Answer 1

7

It looks like the C# compiler removes the call to that method

No, it doesn't - this is just how iterator blocks work. The code inside the iterator block will only start being executed when MoveNext() is called for the first time. If you want to make sure that the whole method gets executed, you could just use:

SomeIteratorMethod().Count();

That will iterate over the whole sequence, throwing away results as it goes (as opposed to a call to ToList for example, which will

If you only want to get as far as the first yield statement, you can use

SomeIteratorMethod().Any();

If you want some code to always execute (e.g. parameter validation) but then the rest should be lazy, you need to split the method in two methods:

public IEnumerable<Foo> SomeIteratorMethod(string mustNotBeNull)
{
    if (mustNotBeNull == null)
    {
        throw ...
    }
    return SomeIteratorMethodImpl(mustNotBeNull);
}

private IEnumerable<Foo> SomeIteratorMethodImpl(string mustNotBeNull)
{
    ... yield new Foo()...
}

Or you could just stop using an iterator block, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.