c# - Generic Method Resolution -


consider following code:

public class tests {     public void test()     {         assert.areequal("int", dosomething(1));     }      public static string dosomething<t>(t value)     {         return "generic";     }      public static string dosomething(int value)     {         return "int";     } } 

as expected, non-generic dosomething method invoked. consider following modification:

public class tests {     public void test()     {         assert.areequal("int", dosomething(1));     }      public static string dosomething<t>(t value)     {         return "generic";     }      public static string dosomething<t>(int value)     {         return "int";     } } 

the thing i've changed adding t type parameter second overload, making generic. note type parameter not used.

that modification causes first dosomething method called. why? compiler has information needs in order choose second method.

can please explain why, or better, point me section of c# specification explains behavior?

in call, you're not specifying type argument - compiler have infer type of t. can't second method, because type parameter never mentioned in declared parameters. therefore, overload not applicable, , ignored.

if specify type argument call, e.g. of

dosomething<int>(1) dosomething<object>(1) dosomething<string>(1) 

... in cases second overload called.

from section 7.6.5.1 of c# 5 spec, (method invocations) when constructing set of candidate methods:

  • if f generic , m has no type argument list, f candidate when:
    • type inference (§7.5.2) succeeds, inferring list of type arguments call, and
    • once inferred type arguments substituted corresponding method type parameters, constructed types in parameter list of f satisfy constraints (§4.4.4), , parameter list of f applicable respect (§7.5.3.1).

as type inference doesn't succeed, second method isn't in candidate set, time real overload resolution, set has single method in (the first one).


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -