Convert.ToString(null)
returns
null
As I expected.
But
Convert.ToString(null as object)
returns
""
Why are these different?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are 2 overloads of
ToStringthat come into play hereThe C# compiler essentially tries to pick the most specific overload which will work with the input. A
nullvalue is convertible to any reference type. In this casestringis more specific thanobjectand hence it will be picked as the winner.In the
null as objectyou’ve solidified the type of the expression asobject. This means it’s no longer compatible with thestringoverload and the compiler picks theobjectoverload 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.