Overloaded logic selection logic

Given the following overloaded methods:

public string Test(long item) { return "Test with a long was called!"; } public string Test(int item) { return "Test with an int was called!"; } public string Test(object item) { return "Test with an object was called!"; } 

When I call Test() by passing short , for example:

 short shortValue = 7; var result = Test(shortValue); 

Why the result value is equal to "Test with an int was called!" instead of "Test with an object was called!" ?

+4
source share
2 answers

Why is the result equal to "Test with int was called!" Instead of "Test with object was called!"?

Converting to int "better" than converting to object , so overloading that takes int is "better" than one that accepts object , and both are applicable as short implicitly converted to both int and object . ( long overloading is also applied, but converting to int better than long ).

See section 7.5.3 of the C # language specification for general overload rules and 7.5.3.3 for "best conversion" rules. It makes little sense to write them here, since they are very long, but the most important aspect is that there is a conversion from int to object , but without conversion from object to int - therefore, conversion to int is more specific and therefore better.

(Partition numbers are given in versions C # 4 and C # 5. You can download C # 5 spec in Word format.)

+7
source

C # specification rules mean that the compiler prefers to convert short to int rather than object . I think this is due to the following rule: 7.5.3.5 Best conversion goal (link to download the C # 5 specification or see the equivalent of C # 1.2 online)

Given the two different types T1 and T2, T1 is a better conversion goal than T2 if at least one of the following is true:

  • There is an implicit conversion from T1 to T2, and there is no implicit conversion from T2 to T1.
  • T1 is a signed integral type, and T2 is an unsigned integral type. [other content omitted]

To rewrite it for this scenario, since there is an implicit conversion from int to object and there is no implicit conversion from object to int , converting to int is the best conversion.

+2
source

All Articles