8

Please check following code

DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();

It returns String.Empty.

Is it correct?

May be it will be better to rise exception in second line of code

Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42

1 Answers1

18

Yes, it's correct. From the documentation

The text representation of the value of the current Nullable<T> object if the HasValue property is true, or an empty string ("") if the HasValue property is false.

Note also that Nullable<T>.Equals and Nullable<T>.GetHashCode do not throw in this case but that Nullable<T>.GetType does throw. This is because Object.Equals, Object.GetHashCode and Object.ToString are overridden for Nullable<T> but that Object.GetType is not (because it can not be as it is not marked as virtual).

jason
  • 236,483
  • 35
  • 423
  • 525
  • ok, thanks for you answer. but how you think is it correct way? because if you will use String tmp = null; tmp.ToString() it will rise exception – Andrei Andrushkevich Dec 28 '10 at 15:40
  • Because a nullable type with `HasValue` as false is not a `null` reference. From a conceptual perspective, a nullable type represents a value type with the possibility of the value being "missing." We use `null` to represent when the value is missing, but this is not the same as a `null` reference. Note that `tmp.Value` will throw in the case of `tmp` being an instance of a nullable type with `HasValue` as false. The value is missing so trying to obtain said value should and does throw accordingly. – jason Dec 28 '10 at 15:44