Let's say I create a generic method, and implement some types, like shown in the code below.
I also have two objects, a Foo
and a Bar
, where Bar
inherits from Foo
.
I then implement the generic method for Foo
.
If I call the method with Bar
, why doesn't it hit the Foo
overload of the method?
I tested the code below and that's what it returns. I am more interested in why that happens.
My question raises because I want to process Bet
and Bar
the same way, so the body of the method would be the same. Although, I cannot see how to do this without either duplicating the code, or creating another method that dispatches to the correct one.
public class Foo
{
}
public class Bar : Foo
{
}
public class Bet : Foo
{
}
public static void Test(Foo foos)
{
Console.WriteLine("You hit Test(Foo)");
}
public static void Test<T>(T generic)
{
Console.WriteLine("You hit Test<T>");
}
void Main()
{
Foo foo = new Foo();
Bar bar = new Bar();
Bet bet = new Bet();
Test(foo); // Prints "You hit Test(Foo)", as expected
Test(bar); // Prints "You hit Test<T>", I expexted "You hit Test(Foo)"
Test(bet); // Prints "You hit Test<T>", I expexted "You hit Test(Foo)"
}