Having this code:
class Program
{
static void Main(string[] args)
{
Check(3);
Console.ReadLine();
}
static void Check(int i)
{
Console.WriteLine("I am an int");
}
static void Check(long i)
{
Console.WriteLine("I am a long");
}
static void Check(byte i)
{
Console.WriteLine("I am a byte");
}
}
Why this code prints "I am an int" and not "I am a long" ?
Why this code prints "I am an int" and not "I am a long" ?
Because the compiler goes through the rules of overload resolution, which are in the C# 5 spec, starting at section 7.5.3.
Both of those are applicable function members (i.e. they'd both be 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 of the argument is int
, and an identity conversion is "better" than a widening conversion (section 7.5.3.3).
Given an implicit conversion C1 that converts from an expression E to a type T1, and an implicit conversion C2 that converts from an expression E to a type T2, C1 is a better conversion than C2 if at least one of the following holds:
- E has a type S and an identity conversion exists from S to T1 but not from S to T2
- ...
Here E
is int
, T1
is int
, and T2
is long
. There's an identity conversion from int
to int
, but not from int
to long
... therefore this rule applies, and the conversion from int
to int
is better than the conversion from int
to long
.
See more on this question at Stackoverflow