简体   繁体   中英

Unexpected behavior from String.Format()

Given the following code, I would expect to an empty result or an exception:

String.Format(null, "Hello")

Instead, the result is the string "Hello". Why is this?

It's working because it's choosing this overload:

public static String Format( IFormatProvider provider, String format, params Object[] args) { ... }

A null provider is OK, and no arguments to the varargs is also OK, and so it just prints out the string.

Intuitively, we might have expected this overload:

public static String Format(String format, Object arg0) { ... }

And of course, if it did choose that, we would have gotten an ArgumentNullException .

It chooses overload

public static string Format(IFormatProvider provider, string format, params object[] args)

because your second argument has type of string (no conversion required). Thus this overload is closer, than overload with two parameters (it requires conversion from string to object ):

public static string Format(string format, object arg0)

You can see the difference by calling:

String.Format(null, 5);

In this case conversion to object is chosen and you have an exception (actually there is no implicit conversion between int and string ).

You can read more on choosing best function member on msdn.

It might be interpreting the request as a call to the String.Format(IFormatProvider provider, string format, params object[] args) override and taking null as the provider and the params but "Hello" as the format, thus returning "Hello".

If you want an empty result use String.Empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM