ToString on null string

2019-04-03 14:50发布

Why does the second one of these produce an exception while the first one doesn't?

string s = null;
MessageBox.Show(s);
MessageBox.Show(s.ToString());

Updated - the exception I can understand, the puzzling bit (to me) is why the first part doesn't show an exception. This isn't anything to do with the Messagebox, as illustrated below.

Eg :

string s = null, msg;
msg = "Message is " + s; //no error
msg = "Message is " + s.ToString(); //error

The first part appears to be implicitly converting a null to a blank string.

8条回答
欢心
2楼-- · 2019-04-03 15:33

because you cannot call instance method ToString() on a null reference.

And MessageBox.Show() is probably implemented to ignore null and print out empty message box.

查看更多
孤傲高冷的网名
3楼-- · 2019-04-03 15:40

The .show function must have null checking and handle it.

查看更多
登录 后发表回答