c# - Generic method overloading and precedence -


i have 2 overloaded generic methods:

t foo<t>(t t) { console.writeline("t"); return t; }  t foo<t>(int i) { console.writeline("int"); return default(t); } 

when try call foo follows on computer:

foo(5); 

i no compiler errors or warnings, , first method generic argument called (i.e. output t). will case in c# incarnations , on platforms? in case, why?

on other hand, if explicitly specify type in generic call:

foo<int>(5); 

the second method int argument called, i.e. output int. why?

i using different argument names in 2 method overloads, output following calls expected:

foo<int>(t: 5);       // output 't' foo<int>(i: 5);       // output 'int' 

if calling first method, can leave out type specification:

foo(t: 5);            // output 't' 

but if try compile this:

foo(i: 5); 

i error the type arguments method 'foo(int)' cannot inferred usage. try specifying type arguments explicitly. why cannot compiler deal call?

note these tests have been performed linqpad on windows 8 x64 system (in case relevant results...)

last question

since specified (by parameter name) should call overload takes int parameter, compiler has no idea pass t.

first question

because of this, foo(5) only matches 1 overload (foo<t>()).
therefore, must call foo<t>().

second question

when explicitly specify type argument (<int>), both overloads applicable.
in case, foo(int) better, since parameter not of generic type.

as per c# spec §7.5.3.2:

  • otherwise, if mp has more specific parameter types mq, mp better mq. let {r1, r2, …, rn} , {s1, s2, …, sn} represent uninstantiated , unexpanded parameter types of mp , mq. mp’s parameter types more specific mq’s if, each parameter, rx not less specific sx, and, @ least 1 parameter, rx more specific sx:
    • a type parameter less specific non-type parameter.

(emphasis added)


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -