OK, I wasn’t quite done. One more variance post!
Smart people: suppose we made IEnumerable<T> covariant in T. What should this program fragment do?
class C : IEnumerable<Giraffe>, IEnumerable<Turtle> {
IEnumerator<Giraffe> IEnumerable<Giraffe>.GetEnumerator() {
yield return new Giraffe();
}
IEnumerator<Turtle> IEnumerable<Turtle>.GetEnumerator() {
yield return new Turtle();
}
// [etc.]
}
class Program {
static void Main() {
IEnumerable<Animal> animals = new C();
Console.WriteLine(animals.First().GetType().ToString());
}
}
Options:
1) Compile-time error.
2) Run-time error.
3) Always enumerate Giraffes.
4) Always enumerate Turtles.
5) Choose Giraffes vs Turtles at runtime.
6) Other, please specify.
And if you like any options other than (1), should this be a compile-time warning?
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using
About Eric Lippert
Eric Lippert is a senior developer on the Microsoft C# compiler team. Before that he worked on the framework of Visual Studio Tools For Office. Before that, he worked on the compilers, runtimes and tools for VBScript, JScript, Windows Script Host and other Microsoft Scripting technologies. He lives in Seattle and spends his free time editing books about programming languages, playing the piano, and trying to keep his tiny sailboat upright in Puget Sound.