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 😉 .
Thankyou verry much exactly what i needed!
Cool! Glad to help.
BB
Nice one. Just what I was after.