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 ?
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 .
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.
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.
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 isnull
But:
string.Format(string, object[])
:
format or args isnull
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With