ToString for null string

Why does the second of them throw an exception, and the first does not work?

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

Updated - an exception that I can understand, a cryptic bit (for me) is why the first part does not show an exception. This has nothing to do with Messagebox, as shown below.

For example:

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

The first part is an implicit conversion of null to empty string.

+13
string tostring null c # exception
Jan 25 2018-11-11T00:
source share
7 answers

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

And MessageBox.Show() is probably implemented to ignore the empty and print the empty message field.

+18
Jan 25 2018-11-12T00:
source share

This is because MessageBox.Show () is implemented using pinvoke, it calls the native Windows function MessageBox (). Which does not mind getting NULL for the lpText argument. C # language has much stricter rules for pure .NET instance methods (e.g. ToString), it always emits code to verify that the object is not null. There is some background information about this in this post.

+12
Jan 25 '11 at 12:52
source share

Behind the scenes, concat is called in your next question / update. For example,

 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. 
+4
Apr 18 '12 at 10:37
source share

You are trying to execute the ToString () method at zero. To execute the method, you need a valid object.

+3
Jan 25 '11 at 12:41
source share

The .show function must have a null check and handle it.

+1
Jan 25 '11 at 12:41
source share

Because the second call expects the s object to satisfy the ToString () method request. therefore, before .Show () is called, s.ToString () failed to attempt to call the method.

Interestingly, although .Show () is implemented correctly, many such methods expect non-empty instances to be passed. This is usually when you use NullObject so that the caller does not have to deal with this behavior.

0
Jan 25 '11 at 12:44
source share

Probably the Show method handles a null value and just doesn't show anything. The second use of s is s.ToString () fails because you do not have a ToString method to run.

0
Jan 25 2018-11-12T00:
source share



All Articles