I have the following code:
[TestMethod]
public void TestFoo()
{
Foo(null);
}
private void Foo (object bar)
{
Console.WriteLine("Foo - object");
}
private void Foo (string bar)
{
Console.WriteLine("Foo - string");
}
and when I run the test "TestFoo()", the console output is "Foo - string". How does the compiler decide which method to call?
It applies the "better conversion" rules (7.4.3.3 of the C# 3 spec) as part of overload resolution (section 7.4.3 in general).
Basically in this case there's a conversion from string
to object
, but not from object
to string
. Following the rules, that means the conversion from null
to string
is better than the one from null
to object
, so the overload with the string
parameter is used.
Overload resolution can get extremely complicated when the following factors get involved:
params
) add to the funBasically overloading can be a real can of worms - where possible, design overloads so that only one of them will ever be a valid target of any given method call, so that you don't need to worry about the detailed rules.
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