String.Format Argument Null Exception

The code below will throw an Argument Null Exception

var test = string.Format("{0}", null); 

However, this will return an empty string

 string something = null; var test = string.Format("{0}", something); 

Just curious to see why the second part of the code does not throw an exception. This is mistake?

+59
c #
Jul 01 '14 at 17:37
source share
3 answers

The difference is that the first part of the code calls string.Format(string, object[]) ... while the second part of the code calls string.Format(string, object) .

null is a valid argument for the second method (it should have been considered the value for the first placeholder), but not the first (where null usually an array of placeholders). In particular, compare the documentation when a NullArgumentException is NullArgumentException :

string.Format(string, object) :
null format

But:

string.Format(string, object[]) :
format or args null

Think of string.Format(string, object) as an implementation of something like:

 public static string Format(string format, Object arg0) { return string.Format(format, new object[] { arg0 } ); } 

So, after a bit of replacement, your code is closer to:

 // Broken code object[] args = null; // No array at all var test = string.Format("{0}", args); // Working code object[] args = new object[] { null }; // Array with 1 value var test = string.Format("{0}", args); 
+74
Jul 01
source share

The second code fragment causes the following overload:

 Format(String, Object) 

Here the value can be zero, as indicated in the documentation.

The first code fragment uses the following overload:

 Format(String, Object[]) 

Here, the second value cannot be null , as indicated in the documentation.

+16
Jul 01
source share

A small point not mentioned by the existing answers, and almost makes the question moot:

Full post for ArgumentNullException :

The value cannot be null.
Parameter Name: args

Also here the null problem is of any type. Casting it to string or object explicitly (or using the C # default() function) would avoid the problem.

0
Jul 09 '14 at 5:08
source share



All Articles