How do I generate a random integer in C#?
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.
Beware that new Random()
is seeded on current timestamp.
If you want to generate just one number you can use:
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
So do not use this code to generate a series of random number.
Why not use int randomNumber = Random.Range(start_range, end_range)
?
Try these simple steps to create random numbers:
Create function:
private int randomnumber(int min, int max)
{
Random rnum = new Random();
return rnum.Next(min, max);
}
Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box.
textBox1.Text = randomnumber(0, 999).ToString();
0 is min and 999 is max. You can change the values to whatever you want.
The numbers generated by the inbuilt Random
class (System.Random) generates pseudo random numbers.
If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider
.
Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.
You can try with random seed value using below:
var rnd = new Random(11111111); //note: seed value is 11111111
string randomDigits = rnd.Next();
var requestNumber = $"SD-{randomDigits}";