How to generate random int number? (C#)
new Random().Next( int.MinValue, int.MaxValue )
For more information, look at the Random class, though please note:
However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers
The Random
class is used to create random numbers. (Pseudo-random that is of course.)
Example:
Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51
If you are going to create more than one random number, you should keep the Random
instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.
You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a truly random number.
using System;
using MiscUtil;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(StaticRandom.Next());
}
}
}
Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
//Function to get random number
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
public static int GetRandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return getrandom .Next(min, max);
}
}