Reputation: 21
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
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.
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
Reputation: 26109
I'm surprised it even compiles. The Program
class needs to implement IEnumerable
.
Upvotes: 0