Generate Random Numbers in C#
C# provides the Random class to generate random numbers based on the seed value.
The following example demonstrates how to generate a random integer.
Random random = new Random();
int num = random.Next();
Call the Next()
method multiple times to get the multiple random numbers, as shown below.
Random random = new Random();
for (int i = 0; i < 4; i++)
{
Console.WriteLine(random.Next());
}
Use the Next(int)
method overload to generate a random integer that is less than the specified maximum value.
The following example generates the positive random numbers that are less than 10.
Random random = new Random();
for (int i = 0; i < 4; i++)
{
Console.WriteLine(random.Next(10)); // returns random integers < 10
}
Use the Next(int min, int max)
overload method to get a random integer that is within a specified range.
Random random = new Random();
for(int i = 0; i < 4; i++)
{
Console.WriteLine(random.Next(10, 20)); // returns random integers >= 10 and < 19
}
The Random
class uses the seed value as a starting value for the pseudo-random number generation algorithm. By default, the Random
class uses the system clock to generate its seed value so that each instance of the Random
class can generate different random numbers.
Two different instances of the Random
class having the same seed value will generate the same random numbers, as shown below.
Random random1 = new Random(10); // seed value 10
for (int i = 0; i < 4; i++){
Console.WriteLine(random1.Next());
}
Random random2 = new Random(10); // seed value 10, the same as in the first
for (int i = 0; i < 4; i++){
Console.WriteLine(random2.Next());
}
Use the following methods of the Random class to generate random numbers.
- Next() Returns a positive random integer within the default range -2,147,483,648 to 2,147,483, 647.
- Next(int) Returns a positive random integer that is less than the specified maximum value.
- Next(int, int) Returns a positive random integer within the specified minimum and maximum range (includes min and excludes max).
- NextDouble() Generates random floating-point number that is greater than or equal to 0.0 and less than 1.0.
- NextByte() Fills the specified array with the random bytes.
Source: Generate Random Numbers in C# (tutorialsteacher.com)
Comments