Surprising overload resolution with Class & Method generics #8143
-
Assuming I have the following code: var a = "public";
var b = new Wrapper<string>("private");
Console.WriteLine("Direct call");
C<string>.Test(a); // [1] prints "Generic"
C<Wrapper<string>>.Test(b); // [2] prints "Specific"
Console.WriteLine("Using wrapper");
C<string>.Indirect(a); // [3] prints "Generic"
C<Wrapper<string>>.Indirect(b); // [4] prints "Generic"
public static class C<T1> {
public static void Indirect(T1? data) {
Test(data);
}
public static void Test<T>(T? data) {
Console.WriteLine("Generic");
}
public static void Test<T>(Wrapper<T>? data) {
Console.WriteLine("Specific");
}
}
public class Wrapper<T> {
public T data;
public Wrapper(T data)
{
this.data = data;
}
} The first two calls ([1] and [2]) behave as expected. The method specialised for What did surprise me was the behavior of call [4]. Even though the involved types should all be the same, overload resolution selected the "Generic" method. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is intended behavior. The call to |
Beta Was this translation helpful? Give feedback.
This is intended behavior. The call to
Test
in theIndirect
is resolved toTest<T>(T? data)
during compilation, at which point there is no knowledge at all about whatT1
can be at runtime.