How long has the implicit convergence of objects been broken?
I have this code:
DateTime d = DateTime.Today;
long l = d.ToBinary();
object o = (long)l;
d = new DateTime((long)o);
When executing this code, I get an error d = new Date..
(last line). It says the argument is out of range; that it is outside the range of high and low ticks. Which seems likely, since using the debugger l
is a huge negative number (and I didn't think ticks could be negative).
Is C # object/long
broken or am I just missing something? I also tried to install DateTimeKind
and did nothing.
Also, this work is done on a 64 bit machine (although it shouldn't matter because of .NET)
source to share
Try this instead:
DateTime d = DateTime.Today;
long l = d.ToBinary();
object o = (long)l;
d = DateTime.FromBinary((long)o);
Please note that I am using the method DateTime.FromBinary
:
Disables the 64-bit binary value and recreates the original serialized DateTime object.
The constructor you called earlier was expecting ticks, as opposed to the serialized form DateTime
.
source to share
You should use DateTime.FromBinary
to recover DateTime
from a binary representation long
obtained with DateTime.ToBinary
.
Several other comments:
-
The conversion from
long
toobject
that you have in your code is an explicit conversion, not an implicit one. -
It is strange that your suspicion would be that such a transformation is violated. Without a doubt, this is an operation that has been proven in battle at least a million times since the inception of .NET.
-
If you are using the debugger (or operators
Console.WriteLine
), you might see thatl
botho
represent the same valuelong
. This would suggest to you that it is not a transformation that is broken, but something else. -
MSDN can be extremely helpful for answering questions like this one. Once you realized that you
l
were very negative, your suspicion must have been that itDateTime.ToBinary
does not represent onlyDateTime.Ticks
. the documentation confirms this.
source to share