Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToString() and .ToString() method in c# [duplicate]

Tags:

c#

I know Convert.ToString(obj) handles null value and ToString(obj) doesn't handle null value.It means it will throw an error if the obj value is null.

ex:- 
object b = null;
textBox1.Text = b.ToString(); // It will throw a null reference exception because the object value is null.

It is correct and working as expected. But,

ex:-
int? c = null;
textBox1.Text = c.ToString();

I tried in this way. But in this case it is not throwing null reference exception error. Why it is not throwing null reference exception error. Can anyone answer?

Suggestions welcome.

like image 252
Aishu Avatar asked May 19 '15 10:05

Aishu


1 Answers

This is because Nullable<int> (which is the Type for which int? is shorthand) is a struct and therefore never null.

int? c = null is actually assigning c.Value to be Null rather than c itself, so c.ToString() is still a valid operation.

like image 52
Steve Lillis Avatar answered Sep 27 '22 22:09

Steve Lillis