Evil Code of the Day: variance and overloading
(Note that this kind of breakage was mentioned a long time ago in Eric Lippert’s blog, although not in this exact form.) Whenever a conversion becomes available where it wasn’t before, overload resolution can change its behaviour. From C# 1 to C# 2 this happened due to delegate variance with method group conversions – now the same thing is true for generic variance for interfaces. What does the following code print? using System; using System.Collections.Generic; class Base { public void Foo(IEnumerable<string> strings) { Console.WriteLine(“Strings”); } } class Derived : Base { public void Foo(IEnumerable<object> objects) { Console.WriteLine(“Objects”); } } class Test { static void Main() { List<string> strings = new List<string>(); new Derived().Foo(strings); } } The correct answer is “it … Continue reading Evil Code of the Day: variance and overloading