I'm reading the famous archived article by Eric Lippert Constraints are not part of the signature. In this article there is an example of code that I'm trying to run in a clean new solution using .NET 2.0:
class Program
{
class Animal { }
class Mammal : Animal { }
class Giraffe : Mammal { }
class Reptile : Animal { }
static void Foo<T>(T t) where T : Reptile
{
}
static void Foo(Animal animal)
{
}
static void Main(string[] args)
{
Foo(new Giraffe());
Console.ReadLine();
}
}
In the article Eric says that:
Most people assume that overload resolution will choose the second overload. In fact, this program produces a compile error saying that T cannot be Giraffe. Is this a compiler bug? No, this behaviour is correct according to the spec.
When I run the code using .NET 2.0 I have no error, the method Foo(Animal animal) is called. The same method called when I pass null
instead of Giraffe
. I understand that the C# team possibly changed something later, but I use .NET 2.0 here! Using C# 9 I see the same behavior. My question is how I can reproduce the error that Eric mentioned in this article? If I can't reproduce it then I may face the error unexpectedly some day in certain circumstances.