Generating Random Numbers

VB.Net provides a very easy way to generate random numbers by providing a seed value. Because the randomness of the number depends on the seed value that you plant and therefore, to obtain a truly random number at unpredictable sequence, the seed must also be a truly random number itself. Hence to get the seed to be truly random, programmers usually use a value converted from the current date and time. As such, the random number is then generated.


Dim Dice As Integer
Dim Rand As New Random(Val(DateTime.Now.Second)) '<- convert current time seconds to a value to be used as seed

Dice = Val(Rand.Next(1,6).ToString()) '<-- provide the lower and upper limit of 1 and 6 of a dice

The random number generated will be between 1 and 6

That shows how random numbers are generated in VB.Net

2 comments

  1. Anonymous // Friday, January 30, 2009 6:37:00 AM  

    Doesn't work. Value of type Datetime cannot be converted to Long.

  2. Fluffy // Monday, February 02, 2009 5:31:00 AM  

    Thanks for identifying the error in the code that you have encountered. As the seconds hand of a clocks keeps moving round the clock, an easier alternative solution will be to simply use and convert this seconds of a current datetime into values instead. The necessary correction has been made to the above codes (colored). Thank you.