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.
.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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With