Home » c# » String.Format Argument Null Exception

String.Format Argument Null Exception

Posted by: admin November 29, 2017 Leave a comment

Questions:

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 ?

Answers:

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); 

Questions:
Answers:

The second code snippet is calling the following overload:

Format(String, Object)

Here the value can be null, as per the documentation.

The first code snippet uses the following overload:

Format(String, Object[])  

Here the second value cannot be null, as per the documentation.

Questions:
Answers:

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

The full message for the ArgumentNullException is:

Value cannot be null.
Parameter name: args

Also part of the issue here is null is of any type. Explicitly casting it to string or object (or use the C# default() feature) would avoid the problem.