Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null literal parameter type overload resolution [duplicate]

Tags:

c#

.net

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?

like image 748
Peter Kelly Avatar asked Sep 13 '11 09:09

Peter Kelly


1 Answers

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.
like image 91
InBetween Avatar answered Oct 21 '22 21:10

InBetween