Generating random numbers in VB 2005

In VB6, I used to generate random numbers using the following code:

Dim nRandomNum As Integer

nRandomNum = Math.Rnd

I see in VB 2005 there is now a RandomNumberGenerator class. Should I be using this rather? And if so, can someone show me a simple example of how to use it?

Who is Participating?
dctuckConnect With a Mentor Commented:
Dim generator As New Random
Dim randomValue As Integer
randomValue = generator.Next(minvalue, maxvalue)
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
One big "gotcha" when using the Random class is the second parameter to the Next() method is NOT included in the return set.


    "Return Value --> A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue."

This is OFTEN missed by new developers!

So if you want values between 1 and 5 INCLUSIVE then you need:

    randomValue = generator.Next(1, 6) ' returns 1 to 5

and NOT:

    randomValue = generator.Next(1, 5) ' returns 1 to 4
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.