Convert.ToString behaves differently for "NULL object" and "NULL string"

I have foo ( object ) and foo2 ( string ) in a C # console application. Code 2 throws an exception, while code 1 is working fine.

Could you explain why this is so (via the MSDN link)?

// Code 1

 object foo = null; string test = Convert.ToString(foo).Substring(0, Convert.ToString(foo).Length >= 5 ? 5 : Convert.ToString(foo).Length); 

// Code 2

 string foo2 = null; string test2 = Convert.ToString(foo2).Substring(0, Convert.ToString(foo2).Length >= 5 ? 5 : Convert.ToString(foo2).Length); 
+7
source share
3 answers

From the documentation of Convert.ToString(string) :

Return value
Type: System.String
the value is returned unchanged.

So null input will result in a null return value.

From the documentation of Convert.ToString(object) :

Return value
Type: System.String
A string representation of the value or String.Empty if the value is null.

(where "Nothing" means "null" here.)

So null input will result in the return value of an empty string (not a null reference).

+28
source

Because:

This is an implementation of Convert.ToString (object value)

 public static string ToString(Object value) { return ToString(value,null); } public static string ToString(Object value, IFormatProvider provider) { IConvertible ic = value as IConvertible; if (ic != null) return ic.ToString(provider); IFormattable formattable = value as IFormattable; if (formattable != null) return formattable.ToString(null, provider); return value == null? String.Empty: value.ToString(); } 

and this is the value of Convert.ToString (string value)

 public static String ToString(String value) { Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here. return value; } 
+3
source

From this Link :

There are 2 ToString overloads here.

 Convert.ToString(object o); Convert.ToString(string s); 

The C # compiler essentially tries to choose the most specific overload that will work with input. A null value is converted to any reference type. In this case, the string is more specific than the object, and therefore it will be selected as the winner.

In an object null as an object, you have strengthened the type of expression as an object. This means that it is no longer compatible with line overloading, and the compiler chooses to overload the object, since it is the only compatible one.

The really hairy details of how this breaking work is described in section 7.4.3 of the C # language specification.

-one
source

All Articles