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
stringtoobject, but not fromobjecttostring. Following the rules, that means the conversion fromnulltostringis better than the one fromnulltoobject, so the overload with thestringparameter 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.