String.Format with null format
Asked Answered
S

2

5

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.

Shirleenshirlene answered 21/10, 2010 at 14:30 Comment(0)
N
11

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.

Neurasthenia answered 21/10, 2010 at 14:31 Comment(4)
And I guess we should toss out a reminder to pick up a copy of RedGate Reflector so looking this up is way easier. ;)Lamentable
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).Edmond
You mean Lutz Roeder's Reflector? (I still haven't accepted the sellout)Leffen
You can also just do right click, go to definition and it has all you need to know.Neurasthenia
B
1

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.

Bethesde answered 21/10, 2010 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.