Why am I getting an exception when passing a null constant, but not when passing a null string reference?

If I run this code:

Console.WriteLine( String.Format( "{0}", null ) ); 

I get an ArgumentNullException , but if I run this code:

 String str = null; Console.WriteLine( String.Format( "{0}", str ) ); 

it works just fine, and the output is an empty string.

Now the two parts look equivalent to me - they both pass the null reference to String.Format() , but the behavior is different.

How is different id behavior possible here?

+59
reference c # argumentnullexception
Dec 14 '12 at 11:10
source share
1 answer

Just decompile the code to find out what is going on.

 string.Format("{0}", null) 

causes 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 this is obvious why the last three options are invalid.

To determine which of the first two to use, the compiler compares the conversion from null to Object to the conversion from null to Object[] . Converting to Object[] is considered "better" because there is a conversion from Object[] to Object , but not vice versa. This is the same logic with which we had:

 Foo(String) Foo(Object) 

and called Foo(null) , he would choose Foo(String) .

So your source code is equivalent:

 object[] values = null; string.Format("{0}", values); 

At this point, I hope you expect an ArgumentNullException - as per the documentation.

+76
Dec 14 '12 at 11:16
source share



All Articles