Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format Argument Null Exception

Tags:

c#

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 ?

like image 739
Raj C Avatar asked Jul 01 '14 17:07

Raj C


People also ask

How do you handle an argument null exception?

To prevent the error, instantiate the object. An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null . To prevent the error, check for a return value that is null and call the second method only if the return value is not null .

What is string format in C#?

In C#, Format() is a string method. This method is used to replace one or more format items in the specified string with the string representation of a specified object.In other words, this method is used to insert the value of the variable or an object or expression into another string.

What is the string .format method used for?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.


2 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);  
like image 50
Jon Skeet Avatar answered Oct 13 '22 21:10

Jon Skeet


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.

like image 27
Servy Avatar answered Oct 13 '22 23:10

Servy