Long Arithmetic not elegant in .NET

P

Phillip Taylor

This doesn't work:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = b - a

sets ans to 0 instead of 1 million. You have to do this:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = (DirectCast(b, Long) - DirectCast(a, Long))

to get around it. Although is there a more elegant way?

Phill
 
P

Phillip Taylor

This doesn't work:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = b - a

sets ans to 0 instead of 1 million. You have to do this:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = (DirectCast(b, Long) - DirectCast(a, Long))

to get around it. Although is there a more elegant way?

Phill

instead of ten million*
 
P

Patrice

The first code snippet works fines here ??? (.NET 2.0). How do you see the
value for ans ?
 
K

kimiraikkonen

This doesn't work:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = b - a

sets ans to 0 instead of 1 million. You have to do this:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = (DirectCast(b, Long) - DirectCast(a, Long))

to get around it. Although is there a more elegant way?

Phill

Tried "Dim ans As Long = b - a" and "Dim ans As Long = (DirectCast(b,
Long) - DirectCast(a, Long))" and they both outputs the same: 10000000

Couldn't notice a difference.
 
T

Tom Dacon

Works fine here, with option strict both on and off.

Tom Dacon
Dacon Software Consulting
 
H

Herfried K. Wagner [MVP]

Phillip Taylor said:
This doesn't work:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = b - a

sets ans to 0 instead of 1 million. You have to do this:

Dim t As DateTime = DateTime.Now
Dim a As Long = t.Ticks

Dim t2 As DateTime = t.AddSeconds(1)
Dim b As Long = t2.Ticks

Dim ans As Long = (DirectCast(b, Long) - DirectCast(a, Long))

to get around it. Although is there a more elegant way?

Both code samples produce the same result.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top