How to generate a random integer in C#

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 2,147,483,648<=value<=2,147,483,647-2,147,483,648 < = value < = 2,147,483, 647
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 min<=value<maxmin < = value < max
// Returns an `int` value greater in the range 10 <= value < 50
int num = random.Next(10,50)

Code

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

Copyright ©2024 Educative, Inc. All rights reserved