Why does this code print “I am int” and not “I am long”?
Because the compiler goes through the overload resolution rules found in the C # 5 specification starting in section 7.5.3.
Both of them are applicable members of the function (that is, both of them are valid for the argument list), but the Check(int)
method is "better" than the Check(long)
method (section 7.5.3.2), because the type is an int
argument and the conversion identities are “better” than advanced conversions (section 7.5.3.3).
Given the implicit conversion of C1, which is converted from the expression E to type T1, and the implicit conversion of C2, which is converted from the expression E to type T2, C1 is a better conversion than C2 if at least one of the following statements
- E is of type S and there is an identity transformation from S to T1, but not from S to T2
- ...
Here E
is int
, T1
is int
, and T2
is long
. There, the conversion of identifiers from int
to int
, but not from int
to long
... therefore this rule applies, and the conversion from int
to int
better than the conversion from int
to long
.
source share