String.Format with a zero format

Can anyone explain why the following happens:

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

Thanks.

+4
source share
2 answers

It causes another overload.

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

The MSDN method link described above.

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

The MSDN method link described above.

+10
source

Since the called overloaded function is determined at compile time, it is determined by the static type of the parameter:

 String.Format(null, "foo") 

calls String.Format(IFormatProvider, string, params Object[]) with an empty IFormatProvider and the format string "foo", which is great.

On the other hand,

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

calls String.Format(string, object) with a null value as the format string that throws an exception.

+1
source

All Articles