Why does Convert.ToString(null) return a different value if you cast null?

前端 未结 2 1645
闹比i
闹比i 2020-12-08 03:53
Convert.ToString(null)

returns

null

As I expected.

But

Convert.ToString(null as object)
         


        
2条回答
  •  [愿得一人]
    2020-12-08 04:22

    There are 2 overloads of ToString that come into play here

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

    The C# compiler essentially tries to pick the most specific overload which will work with the input. A null value is convertible to any reference type. In this case string is more specific than object and hence it will be picked as the winner.

    In the null as object you've solidified the type of the expression as object. This means it's no longer compatible with the string overload and the compiler picks the object overload as it's the only compatible one remaining.

    The really hairy details of how this tie breaking works is covered in section 7.4.3 of the C# language spec.

提交回复
热议问题