Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?

selectedItem has two fields:

  • int? _cost
  • string _serialNumber

In this example, _cost and _serialNumber of selectedItem are BOTH null. I am reading through the fields of selectedItem via their properties, and filling in textboxes with their values, when...

TextBox1.Text = selectedItem.Cost.ToString(); //no error TextBox2.Text = selectedItem.SerialNumber.ToString(); //error 

I understand that SerialNumber.ToString() is redundant (because it is already a string), but I don't understand why this causes this exception:

Nullable object must have a value.

  • int? _cost is nullable, and does not have a value, yet it does not give me the exception.
  • string _serialNumber is nullable, and does not have a value, yet it does give me the exception.

This question touches on it, the guy is essentially asking the same thing, but there is no designated answer, and it also doesn't explain why a nullable int? For example, can I use .ToString() on a nullable int but not on a null string?

like image 820
CptSupermrkt Avatar asked Jul 12 '12 07:07

CptSupermrkt


People also ask

What happens if you do a ToString on a null?

.ToString() It will not handle NULL values; it will throw a NULL reference exception error.

What happens if you call ToString on null Java?

"Returns the result of calling toString for a non- null argument and 'null' for a null argument." "if the argument is null , then a string equal to "null"; otherwise, the value of obj. toString() is returned."

Does ToString return null?

toString() returning null would be very bad API design. Clearly, if you are able to call toString() on it, the object is clearly not null. Otherwise, there would be a NullPointerException .

Does ToString work on null in Java?

Null and toString()toString() is only called implicitly if the object passed isn't null. If it is, the literal "null" is printed instead.


1 Answers

Because string type's null really points to nothing, there isn't any object in memory.
But int? type(nullable) even with value set to null still points to some object.
If you read Jeffrey Richter's "CLR via C#" you'll find out that nullable type are just facade classes for common types with some incapsulated logics in order to make work with DB null more convenient.

Check msdn to learn about nullable types.

like image 116
Johnny_D Avatar answered Sep 20 '22 10:09

Johnny_D