The Random
class in C# provides defined methods that generate random integers. The most widely used method to generate random integers from the Random
class is Next()
.
The Random.Next()
method has three overloaded forms:
Next()
: Returns a random int
value within the range
int num = random.Next();
Next(int max)
: Returns a random int
value less than max
// Returns a random integer less than 50
int num = random.Next(50);
Next(int min, int max)
: Returns an int
in the range
// Returns an `int` value greater in the range 10 <= value < 50
int num = random.Next(10,50)
The code snippet below illustrates the usage of the three methods discussed above:
class RandomGenerator{static void Main(){System.Random random = new System.Random();System.Console.WriteLine(random.Next());System.Console.WriteLine(random.Next(50));System.Console.WriteLine(random.Next(10,50));}}
Free Resources