DEV Community

Discussion on: How do you do random?

Collapse
 
programazing profile image
Christopher C. Johnson • Edited

The quick and dirty way in C# to get one random number is:

var randomNumber = new Random().Next(1, 10)

Keep in mind that Random() initializes with the current timestamp so you can't use it in rapid succession and expect a random result.

static void Main(string[] args)
{
     int randomSingle = GetSingleRandomNumber(min: 1, max: 10);

     Console.WriteLine(randomSingle);

     Console.WriteLine(Environment.NewLine);

     List<int> randomList = ListOfRandomNumbers
(min: 1, max: 10, numberOfItems: 5);

     foreach (var number in randomList)
     {
         Console.WriteLine(number);
     }

     Console.ReadKey();
 }

 static int GetSingleRandomNumber(int min, int max)
 {
     return new Random().Next(min, max);
 }

 static List<int> ListOfRandomNumbers
(int min, int max, int numberOfItems)
 {
      var output = new List<int>();

      for (int i = 0; i < numberOfItems; i++)
      {
         output.Add(new Random().Next(min, max));
      }

      return output;
 }

It's important to note what we're doing in the two functions. We're always adding a new Random() i.e

output.Add(new Random().Next(min, max));

Why? Because we get a new timestamp when we do so.

If instead, you did something like this:

var random = new Random();
for (int i = 0; i < numberOfItems; i++)
{
     output.Add(random.Next(min, max));
}

You'd end up with several repeating numbers as it's calculating off the same timestamp. This is fine for small sets of random numbers just don't go newing up Random() for a large set.