8

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.

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
Aishu
  • 1,310
  • 6
  • 28
  • 52

2 Answers2

9

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.

Steve Lillis
  • 3,263
  • 5
  • 22
  • 41
2

Nullable<T> is a struct/value type. The actual nullable isn't null, but the value is. object is a class/reference type.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445