Ads by ProfitSence
Close

C# Generate a random int number.

Last Updated on Wednesday 5th Oct 2022

c# random number generator

Random Class

Represents a pseudo-random number generator, which is an algorithm that produces a sequence of numbers that meet certain statistical requirements for randomness.

			
					public class Random

			
	

The Random class is used to create random numbers.

c# random number

			
					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.

c# random

Create a Random object

			
					Random rand = new Random();

			
	

and use it

			
					int randomNumber = rand.Next(min, max);

			
	
  • You don't have to initialize new Random() every time you need a random number, initiate one Random then use it as many times as you need inside a loop.

pick a number between 1 and 30

			
					using System;
class HelloWorld {
  static void Main() {

    Random rand = new Random();
    int randomNumber = rand.Next(1, 30);
    Console.WriteLine(randomNumber);
  }
}

			
	

random number 1 7

			
					using System;
class HelloWorld {
  static void Main() {

    Random rand = new Random();
    int randomNumber = rand.Next(1, 7);
    Console.WriteLine(randomNumber);
  }
}

			
	

random number between 1 and 23

			
					using System;
class HelloWorld {
  static void Main() {

    Random rand = new Random();
    int randomNumber = rand.Next(1, 23);
    Console.WriteLine(randomNumber);
  }
}

			
	

References