I have this example C# code:
class Stuff { } // empty class
void Main()
{
var list = new List<Stuff> {
new Stuff(),
new Stuff()
};
Fun(list);
}
void Fun<T>(List<T> a)
{
Debug.Log("called List<T> Fun");
foreach (T t in a) {
Fun(t);
}
}
void Fun(Stuff a)
{
Debug.Log("called Stuff Fun");
}
void Fun<T>(T a)
{
Debug.Log("called T Fun");
}
Calling Main() ends up printing:
called List<T> Fun
called T Fun
called T Fun
I don't understand why the compiler is able to call Fun<T>(List<T> a)
as expected, but then does not know to call Fun(Stuff a)
, which is more specific than Fun<T>(T a)
. Does it not know for sure at compile time that T is Stuff
in this case? Printing typeof(T)
inside Fun<T>(List<T> a)
gives "Stuff" as expected, but that is not proof of anything...
Adding a Fun(List<Stuff> a)
method works but is undesirable (lots of different possible types for Lists in the project, and the behaviour is supposed to be the same for all of them).
I have tried searching for this problem but couldn't phrase it in a way that I could find it. Sorry if someone asked this before (which is likely!).