Note This is not a question about how to implement or emulate duck typing in C#...
For several years I was under the impression that certai
There's no chicken and egg: foreach
could depend on IEnumerable
since IEnumerable
doesn't depend on foreach
. The reason foreach is permitted on collections not implementing IEnumerable
is probably largely historic:
In C#, it is not strictly necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach; as long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of allowing you to define the return type of Current to be more specific than object, thereby providing type-safety.
Furthermore, not all chicken and egg problems are actually problems: for example a function can call itself (recursion!) or a reference type can contain itself (like a linked list).
So when using
came around why would they use something as tricky to specify as duck typing when they can simply say: implement IDisposable
? Fundamentally, by using duck typing you're doing an end-run around the type system, which is only useful when the type system is insufficient (or impractical) to address a problem.