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条回答
Explosion°爆炸
2楼-- · 2019-04-03 15:14

Because, the second call is expecting an object of "s" to satisfy a ToString() method request. so, before .Show() is called, the s.ToString() would failed with an attempt to call a method.

Interestingly, While .Show() is implemented correctly, many such methods expect non null instances to be passed in. Usually, that is when you use a NullObject pattern so that the caller should not have to deal with this kind of behavior.

查看更多
戒情不戒烟
3楼-- · 2019-04-03 15:18

It is because MessageBox.Show() is implemented with pinvoke, it calls the native Windows MessageBox() function. Which doesn't mind getting a NULL for the lpText argument. The C# language has much stricter rules for pure .NET instance methods (like ToString), it always emits code to verify that the object isn't null. There's some background info on that in this blog post.

查看更多
Root(大扎)
4楼-- · 2019-04-03 15:22

Probably the Show method handles a null value and just shows nothing. The second use of s - s.ToString() fails because you there is no ToString method to run.

查看更多
在下西门庆
5楼-- · 2019-04-03 15:23

You are trying to execute the ToString() method on a null. You need a valid object in order to execute a method.

查看更多
一纸荒年 Trace。
6楼-- · 2019-04-03 15:28

As this question ranks quite high on Google for a search for "c# toString null", I would like to add that the Convert.ToString(null) method would return an empty string.

However, just to reaffirm the other answers, you can use string.Concat("string", null) in this example.

查看更多
▲ chillily
7楼-- · 2019-04-03 15:32

Behind the scenes concat is being called in your follow up question / update E.g

string snull = null;

string msg = "hello" + snull;

// is equivalent to the line below and concat handles the null string for you.
string msg = String.Concat("hello", snull);

// second example fails because of the toString on the null object
string msg = String.Concat("hello", snull.ToString());

//String.Format, String.Convert, String.Concat all handle null objects nicely.
查看更多
登录 后发表回答