I’ve started reading Jon Skeet’s early access version of his book, which contains sections on C# 4.0, and one thing struck me. Unfortunately I don’t have Visual Studio 2010 available so I thought I’d just ask here instead and see if anyone knew the answer.
If I have the following code, a mixture of existing code, and new code:
public void SomeMethod(Int32 x, Int32 y) { ... }
public void SomeMethod(Int32 x, Int32 y, Int32 z = 0) { ... }
Will the compiler complain either at the definition site or the call site about possible ambiguity?
For instance, what will this piece of code actually do?
SomeClass sc = new SomeClass();
sc.SomeMethod(15, 23);
Will it compile? Will it call the one without the z parameter, or will it call the one with the z parameter?
It will compile without warnings and will choose the first overload.
With the introduction of optional and named parameters, the overload resolution mechanism of C# has become really complicated. In this specific case, it makes sense however. As usual, the compiler will choose the most specific overload that matches the arguments.
I don’t believe this specific case is much different from C# 1.0:
which works identically (in terms of overload resolution).
Follow up answer: I don’t think so. I’m afraid you’ll have to manually specify the default argument in the method call. However, if
xoryparameter had a different name like:you could choose the second overload with: