C# provides the Random class to generate random numbers based on the seed value.
Use the following methods of the Random class to generate random numbers.
Source: Generate Random Numbers in C# (tutorialsteacher.com)
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());
}