If I run this code:
Console.WriteLine( String.Format( "{0}", null ) );
I get a ArgumentNullException
but if I run this code:
String str = null; Console.WriteLine( String.Format( "{0}", str ) );
it runs just fine and the output is an empty string.
Now the two piece look equivalent to me - they both pass a null reference into String.Format()
yet the behavior is different.
How id different behavior possible here?
You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does. For more information on declaring and initializing arrays, see Arrays and Arrays. You get a null return value from a method, and then call a method on the returned type.
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
[Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.
Just decompile the code to work out what's going on.
string.Format("{0}", null)
calls the most specific applicable overload, which is string.Format(string, object[])
.
The overloads of string.Format
are:
Format(String, Object) Format(String, Object[]) Format(IFormatProvider, String, Object[]) Format(String, Object, Object) Format(String, Object, Object, Object)
Hopefully it's obvious why the last three options are invalid.
To work out which of the first two to use, the compiler compares the conversion from null
to Object
to the conversion from null
to Object[]
. The conversion to Object[]
is deemed "better" because there's a conversion from Object[]
to Object
, but not vice versa. This is the same logic by which if we had:
Foo(String) Foo(Object)
and called Foo(null)
, it would pick Foo(String)
.
So your original code is equivalent to:
object[] values = null; string.Format("{0}", values);
At this point, hopefully you'd expect an ArgumentNullException
- 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