Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded method selection logic

Tags:

c#

overloading

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(), passing a short, like this:

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

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

like image 480
Karl Anderson Avatar asked Jan 13 '23 07:01

Karl Anderson


1 Answers

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

The conversion to int is "better" than the conversion to object, so the overload taking int is "better" than the one taking object - and both are applicable as short is implicitly convertible to both int and object. (The overload taking long is also applicable, but the conversion to int is better than the one to long, too.)

See section 7.5.3 of the C# language specification for general overloading rules, and 7.5.3.3 for the rules about "better conversions". There's little point in writing them all out here, as they're very long - but the most important aspect is that there's a conversion from int to object but no conversion from object to int - so the conversion to int is more specific, and therefore better.

(Section numbers are from the C# 4 and C# 5 versions. You can download the C# 5 spec in Word format.)

like image 178
Jon Skeet Avatar answered Jan 22 '23 06:01

Jon Skeet