开发者

String.Format with null format

开发者 https://www.devze.com 2023-01-21 13:34 出处:网络
Can anyone explain why the following occurs: String.Format(null, \"foo\") // Returns foo String.Format((string)null, \"foo\") // Throws ArgumentNullException:

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消