views:

62

answers:

2

Hi,

Can anyone explain why the following occurs:

String.Format(null, "foo") // Returns foo
String.Format((string)null, "foo") // Throws ArgumentNullException:
                                   // Value cannot be null. 
                                   // Parameter name: format

Thanks.

+9  A: 

Its calling a different overload.

string.Format(null, "");  
//calls 
public static string Format(IFormatProvider provider, string format, params object[] args);

MSDN Method Link describing above.

string.Format((string)null, "");
//Calls (and this one throws ArgumentException)
public static string Format(string format, object arg0);

MSDN Method Link describing above.

Nix
And I guess we should toss out a reminder to pick up a copy of RedGate Reflector so looking this up is way easier. ;)
drachenstern
Umm... I'd much rather go look at the MSDN documents than dig into Reflector for this kind of info. Or did I miss a joke somewhere (and yes, often reflector is good, everybody should have it).
Chris
You mean Lutz Roeder's Reflector? (I still haven't accepted the sellout)
James B
You can also just do right click, go to definition and it has all you need to know.
Nix
+1  A: 

Because which overloaded function is called gets determined at compile time based on the static type of the parameter:

String.Format(null, "foo")

calls String.Format(IFormatProvider, string, params Object[]) with an empty IFormatProvider and a formatting string of "foo", which is perfectly fine.

On the other hand,

String.Format((string)null, "foo")

calls String.Format(string, object) with null as a formatting string, which throws an exception.

Heinzi