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)

+2


source to share


3 answers


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

.

+4


source


Who Said ToBinary () gets Ticks?

I guess it should look like this:



DateTime d = DateTime.Today;
long l = d.Ticks;
object o = l;
d = new DateTime((long)o);

      

+3


source


You should use DateTime.FromBinary

to recover DateTime

from a binary representation long

obtained with DateTime.ToBinary

.

Several other comments:

  • The conversion from long

    to object

    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 that l

    both o

    represent the same value long

    . 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 it DateTime.ToBinary

    does not represent only DateTime.Ticks

    . the documentation confirms this.

0


source







All Articles