How can I seed the Random object in VB with Now.Ticks?

  • Thread starter Thread starter Ken Dopierala Jr.
  • Start date Start date
K

Ken Dopierala Jr.

Hi,

Here is C# code:

Random rdm1 = new

Random(unchecked((int)DateTime.Now.Ticks));

Can I do this in VB? I've tried CType(DateTime.Now.Ticks, Integer) and
CInt(DateTime.Now.Ticks) but both of them error out because the number is
too large. How can I do the cast like C# does? Thanks! Ken.
 
Hi Ken,

C# is very kind. It says that if you have a Long and want it to become an
Int then enclose it in 'unchecked' and it'll chop off the bit that you don't
want.
IntValue = unchecked ((int) LongValue);

VB doesn't do this for us. We have to do it ourselves.

Dim LongValue As Long = &hFFFFFFFFFFFFFF
Dim IntValue As Integer = CInt (LongValue And &hFFFFFFFF&)

The '&h' at the front says that it's a number in hex while the '&' at the
end says that it's a Long value.

Regards,
Fergus
 
Hi everybody,

Here's a test:

1
Dim LongValue As Long = &hFFFFFFFFFFFFFF
Dim IntValue As Integer = CInt (LongValue And &hFFFFFFFF&)
2
Dim LongValue As Long = &hFFFFFFFFFFFFFF And &hFFFFFFFF&
Dim IntValue As Integer = CInt (LongValue)

What's the difference, if any, and if there is, can you explain why ?

Regards,
Fergus
 
Just use the Environment.TickCount property:

Dim r As New Random(Environment.TickCount)
 
Back
Top