Why does C# allow the following method overload:
void F(int a) { Console.WriteLine(1); }
void F(int? a) { Console.WriteLine(2); }
If I run that code:
A a = new A();
a.F(1);
it prints 1
. How does the compiler know which one to invoke. Isn't it ambiguous?
I thought the idea behind nullable types is that you might pass the value of the right type in or you might pass in null
. So I should be able to call the first F
with (1)
and second F
with (1)
or (null)
.
I have a runnable example here.
Update: After reading the answer, my confusion stemmed from that fact that I thought that nullable params were synonymous with optional params.
Indeed, replacing the second method with void F(int a = 0);
leads to a compilation error.
Nullable<int>
andint
are two different types. – P.Brian.Mackey May 4 '18 at 20:51Nullable
, right? I can pass in1
and it will turn it into aNullable<int>
? – pushkin May 4 '18 at 21:081
literal is of typeint
. Since there is overload which takes exactly this type - it's preferred over another overload, to which type your argument (of typeint
) is implicitly convertible. That's quite common, the same happens if for example you have overloads withint
andobject
. – Evk May 4 '18 at 21:15