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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And I guess we should toss out a reminder to pick up a copy of RedGate Reflector so looking this up is way easier. ;)
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).
You mean Lutz Roeder's Reflector? (I still haven't accepted the sellout)
You can also just do right click, go to definition and it has all you need to know.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.