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
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
Yes, it's correct. From the documentation
The text representation of the value of the current
Nullable<T>
object if theHasValue
property is true, or an empty string (""
) if theHasValue
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
).
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.