Why does changing a type to dynamic cause my C# code to raise an exception?

The following C# program does what I expect, which is to output "First," "Second", "Third." However, when I change the type of foo in Main to dynamic, it raises an exception that says:

"Cannot implicitly convert type 'MyProgram.Program' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)"

Why does changing the type to dynamic break the code in this way?

Thanks!

using System;

namespace TestForEach
{
class Program
{
    private int idx = -1;
    public Program GetEnumerator() {
        return this;
    }
    public string Current
    {
        get {
            string[] arr = { "First", "Second", "Third" };
            return arr[idx];
        }
    }

    public Boolean MoveNext()
    {
        return ++idx < 3;
    }

    static void Main(string[] args)
    {
        Program foo = new Program();
        foreach (var i in foo)
        {
            System.Console.WriteLine(i);
        }
        System.Console.ReadKey();
    }
}
}

Upvotes: 2

Views: 86

Answers (2)

drstevens
drstevens

Reputation: 2913

My guess is that it is because your Program implements the appropriate methods in order to be considered an iterator by the compiler.

An iterator is invoked from client code by using a foreach statement. For example, you can create an iterator for a class that returns the elements in reverse order, or that performs an operation on each element before the iterator returns it. When you create an iterator for your class or struct, you do not have to implement the whole IEnumerator interface. When the compiler detects your iterator, it will automatically generate the Current, MoveNext and Dispose methods of the IEnumerator or IEnumerator(Of T) interface.

When using the dynamic keyword, the compiler is unable to detect that Program is being used in in iterable context. Because of this, it does not generate the appropriate code in order for it to be used in a foreach loop.

Upvotes: 1

Brannon
Brannon

Reputation: 26109

I'm surprised it even compiles. The Program class needs to implement IEnumerable.

Upvotes: 0

Related Questions