Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString on null string

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.

like image 297
MartW Avatar asked Jan 25 '11 12:01

MartW


People also ask

Can you ToString a null?

.ToString()Handles NULL values even if variable value becomes null, it doesn't show the exception. 1. It will not handle NULL values; it will throw a NULL reference exception error. 2.

Does ToString work on null Java?

toString(Object) essentially do the same thing: call the toString() method on a passed-in object. This is the case as long as it's not null or it doesn't return the string "null" when null is passed to them.

Can ToString return null C#?

No method can be called on a null object. If you try to call ToString() on a null object it will throw a NullReferenceException . The conclusion “if it returns null still then the object is null” is not possible and thus wrong.


2 Answers

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.

like image 102
Axarydax Avatar answered Oct 05 '22 05:10

Axarydax


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.

like image 27
Hans Passant Avatar answered Oct 05 '22 04:10

Hans Passant