Possible Duplicate:
How does the method overload resolution system decide which method to call when a null value is passed?
This is a question about why the compiler chooses a certain overload when passed a null literal as a parameter, demonstrated by string.Format overloads.
string.Format throws an ArgumentNullException
when using null literal for args parameter.
string.Format("foo {0}", null);
The Format method has some overloads.
string.Format(string, object);
string.Format(string, object[]);
string.Format(IFormatProvider, string, object[]);
Running through the decompiled code, the exception for the null literal args is thrown from the second method. However, the following examples call the first method above (as expected) and then that calls the second which calls the third eventually returning just "foo".
string x = null;
string.Format("foo {0}", x);
string y;
string.Format("foo {0}", y = null);
But string.Format("foo {0}", null)
calls the second method above and results in a null exception. Why does the compiler decide that the null literal matches the second method signature instead of the first in this case?
I would simply guess that object[]
is more specific than object
and being null
assignable to object[]
the former is picked. (7.5.3.2 Better function member in the C# specs).
Same happens if you try:
void Foo(object o) {}
void Foo(object[] arr) {}
Foo(null); //Foo(object[]) gets called.
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