Assume that I have these two overloaded functions.
public static void Main(string[]args)
{
int x=3;
fn(x);
}
static void fn(double x)
{
Console.WriteLine("Double");
}
static void fn(float x)
{
Console.WriteLine("Float");
}
Why will the compiler choose the float function?
It follows the rules of section 7.5.3.2 of the C# 4 spec.
int
is implicitly convertible to both float
and double
, so both candidate methods are applicable. However, the conversion from int
to float
is "better than" the conversion from int
to double
according to section 7.5.3.2-7.5.3.5:
Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:
- An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists
- ... [irrelevant in this case]
Here, there's an implicit conversion from float
to double
, but no implicit conversion from double
to float
- so float
is a better conversion target than double
.
Jon's answer is, of course, right. To add a bit more detail: the design principle here is that the "more specific" method is better. If you had:
void M(object x){}
void M(Animal x){}
void M(Giraffe x){}
and you called M(new Giraffe())
obviously you would want the exact match. If you called M(new Tiger())
, the best match is "Animal" because a tiger is a kind of animal, a tiger is a kind of object, but animal is more specific than object. How do we know that animal is more specific than object? Because every animal is an object, but not every object is an animal, so animal must be more specific.
If you called M(null)
we would therefore pick the giraffe version. Giraffe is more specific than Animal because every giraffe is an animal but not every animal is a giraffe.
In your example, float is better than double because it is more specific. Every float can be converted to double, but not every double can be converted to float, so float is more specific. Just as every animal can be converted to object but not every object can be converted to animal, so animal is more specific.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With