C# – Get a Random Number Between x and y

Here’s a quick function for getting random numbers in C#:

    Random rnd = new Random();
    protected int GetRandomInt(int min, int max)
    {
        return rnd.Next(min,max);
    }

    int myInt = GetRandomInt(5, 1000); //gives in random integer between 5 & 1000

Notice that you have to declare your instance of the Random class outside of the GetRandomInt function if you are going to be running this in a loop.

“Why is this?” you ask.

Well, the Random class actually generates pseudo random numbers, with the “seed” for the randomizer being the system time. If your loop is sufficiently fast, the system clock time will not appear different to the randomizer and each new instance of the Random class would start off with the same seed and give you the same pseudo random number.

I tried the function with Random rnd = new Random() inside the GetRandomInt function and ran it through a loop that had 150 iterations and several additional calculations.   I got the same random number 10-20 times before it would switch (see the image with all the 8’s highlighted).

Using the same instance of the Random class lets its Next() function take into account previously returned numbers, and you get some mostly random numbers ;-) .

3 Responses to C# – Get a Random Number Between x and y

  1. Chryses Core February 14, 2009 at 6:01 pm #

    Thankyou verry much exactly what i needed!

  2. Byron Bennett February 14, 2009 at 8:04 pm #

    Cool! Glad to help.
    BB

  3. Craig January 13, 2010 at 8:43 am #

    Nice one. Just what I was after.

Powered by WordPress. Designed by Woo Themes