Unexpected behavior of String.Format ()

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

String.Format(null, "Hello") 

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

+4
source share
3 answers

It works because it selects this overload:

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

A null provider is fine, and no arguments for varargs are suitable either, and so it just prints the string.

Intuitively, we could expect this overload:

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

And, of course, if he chose this, we would get an ArgumentNullException .

+10
source

He chooses overload

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

because your second argument is of type string (without the need for conversion). Thus, this overload is closer than overload with two parameters (conversion from string to object is required):

 public static string Format(string format, object arg0) 

You can see the difference by calling:

 String.Format(null, 5); 

In this case, the conversion to the object is selected, and you have an exception (in fact, there is no implicit conversion between int and string ).

You can learn more about choosing a list of the best features in msdn.

+4
source

Perhaps he interprets the request as a call to String.Format (provider IFormatProvider, string format, params object [] args) overrides and accepts null as the provider and parameters, but "Hello" as the format, thus returning "Hello".

If you want an empty result to use String.Empty

+2
source

Source: https://habr.com/ru/post/1412872/


All Articles