Is Nullable DateTime work correct?
Asked Answered
S

1

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

Spahi answered 28/12, 2010 at 15:26 Comment(0)
E
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).

Edmondson answered 28/12, 2010 at 15:29 Comment(2)
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 exceptionSpahi
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.Edmondson

© 2022 - 2024 — McMap. All rights reserved.