String.Format Argument Null Exception

The below code will throw Argument Null Exception

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

However, this will give back an empty string

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

Just curious to know why the second piece of code doesn't throw up exception. Is this a bug ?

Jon Skeet
people
quotationmark

The difference is that the first piece of code is calling string.Format(string, object[])... whereas the second piece of code is calling string.Format(string, object).

null is a valid argument for the second method (it's just expected to be the value for the first placeholder), but not the first (where the null would usually be the array of placeholders). In particular, compare the documentation for when NullArgumentException is thrown:

string.Format(string, object):
format is null

But:

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

Think of string.Format(string, object) as being implemented 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); 

people

See more on this question at Stackoverflow