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?
Just decompile the code to work out what’s going on.
calls the most specific applicable overload, which is
string.Format(string, object[]).The overloads of
string.Formatare: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
nulltoObjectto the conversion fromnulltoObject[]. The conversion toObject[]is deemed “better” because there’s a conversion fromObject[]toObject, but not vice versa. This is the same logic by which if we had:and called
Foo(null), it would pickFoo(String).So your original code is equivalent to:
At this point, hopefully you’d expect an
ArgumentNullException– as per the documentation.