Random numbers – a .Net function to return a random number

By Chris Gaskell

A random number generator I put together as an example for a collegue. Thought I would share it here, it uses ticks as the seed.

Public Shared Function RandomNumber(ByVal MaxNumber As Integer, _
ByVal MinNumber As Integer) As Integer

‘initialize random number generator
Dim r As New Random(System.DateTime.Now.Ticks)
Return r.Next(MinNumber, MaxNumber)

End Function

3 Responses to “Random numbers – a .Net function to return a random number”

  1. Phil Winstanley Says:

    Check out this article, it covers why Random() isn’t very Random() :-)

    http://www.codinghorror.com/blog/archives/000728.html

  2. Terry Cornwell Says:

    ^ see above, also, in a recent implementation I needed to generate a random string for a password (a dictionary would of been so much better). After a while I noticed just how non-random my random passwords were. So, I went with this

    // Create a random seed
    byte[] randomBytes = new byte[4];
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    rng.GetBytes(randomBytes);

    // Convert 4 bytes into a 32-bit integer value.
    seed = (randomBytes[0] & 0×7f)

  3. Terry Cornwell Says:

    Add this to last post DUH…..

    // Now, this is real randomization.
    Random random = new Random(seed);

Leave a Reply