1

I have encountered the code something like this

int? x = new int();
x = null;
var y = x.toString();

My understanding is that it should throw a null reference exception. But the code is not breaking and I am getting the value of y as "". Please let me understand that what's happening here in behind.

Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37
  • https://stackoverflow.com/questions/2449008/nullable-tostring, https://stackoverflow.com/questions/1445766/c-sharp-nullabledatetime-to-string – CodeCaster Mar 27 '18 at 06:13
  • In short, because `int? x = null` creates a new `Nullable` which is _not_ null. See also https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/nullable.cs#L74. Though the links above don't really explain that. – CodeCaster Mar 27 '18 at 06:14
  • @CodeCaster yes actually the above links asserts my statement but don't explain that why and how it happens. – Vivek Mishra Mar 27 '18 at 06:16
  • I am looking for better explanation that why it happens. – Vivek Mishra Mar 27 '18 at 06:18
  • 1
    @VIVEK See https://stackoverflow.com/questions/11446838/why-does-tostring-on-a-null-string-cause-a-null-error-when-tostring-works for explanation – Magnus Mar 27 '18 at 06:19
  • @Magnus thanx. It explains me well. – Vivek Mishra Mar 27 '18 at 06:23

1 Answers1

0

Because it is not null. You are setting null the value of Nullable<int>, which is designed to return an empty string if the value is null.

ForeverZer0
  • 2,379
  • 1
  • 24
  • 32