ZetCode

C# Random

last modified June 16, 2022

In this article we show how to generate random values in C# with the built-in Random class.

The 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.

Random number generator

Random number generator (RNG) generates a set of values that do not display any distinguishable patterns in their appearance. There are two categories of random number generators: hardware random-number generators and pseudo-random number generators. Hardware random-number generators are believed to produce genuine random numbers. Pseudo-random number generators generate values based on software algorithms; they produce values that look random. But these values are deterministic and can be reproduced, if the algorithm is known.

Random generators are used in gambling, gaming, simulations, or cryptography.

Note: For security purposes, cryptographically secure pseudo-random number generators must be used.

To improve the pseudo random-number generators, operating systems use environmental noise collected from device drivers, user input latency, or jitter from one or more hardware components. This is the core of the cryptographically secure pseudo-random number generators.

The seed

The seed is a value which initializes the random number generator. Random number generators produce values by performing some operation on a previous value. When the algorithm starts, the seed is the initial value on which the generator operates. The most important and difficult part of the generators is to provide a seed that is close to a truly random number.

var rnd = new Random();

This constructor creates a random number generator with a default seed.

Note: Since 2016, in .NET Core the default seed has been changed from Environment.TickCount to Guid.NewGuid().GetHashCode(). It is safe to create several random instances in a loop.

C# random numbers

In the first example, we generate some random numbers.

Program.cs
var rand = new Random();

Console.WriteLine(rand.NextDouble());
Console.WriteLine(rand.NextInt64());

var buf = new byte[8];
rand.NextBytes(buf);

Console.WriteLine(string.Join(" ", buf));

The example generates and prints random doubles, integers, and bytes.

var rand = new Random();

A new instance of the Rando class is created.

Console.WriteLine(rand.NextDouble());

The NextDouble method returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0.

Console.WriteLine(rand.NextInt64());

The NextInt64 method returns a non-negative random integer.

var buf = new byte[8];
rand.NextBytes(buf);

We create an array of random bytes with NextBytes method; it fills the elements of a specified array of bytes with random numbers.

$ dotnet run
0.0746532268944834
7374871010421669053
149 132 170 234 101 204 104 37

C# random Next

The Next method returns a random integer. We can specify the lower and upper limits for the random numbers.

There are three overloaded methods:

Program.cs
var rand = new Random();

Console.WriteLine(rand.Next());
Console.WriteLine(rand.Next(5));
Console.WriteLine(rand.Next(10, 20));

The example prints three random numbers.

$ dotnet run
741804443
3
11

C# pick random element

In the next example, we pick a random element from a collection.

Program.cs
var rand = new Random();

var vals = new List<int> {1, 2, 3, 4, 5, 6, 7, 8};

var r1 = vals[rand.Next(vals.Count)];
var r2 = vals[rand.Next(vals.Count)];

Console.WriteLine(r1);
Console.WriteLine(r2);

We print two elements randomly from a list of integers. The upper limit is non-inclusive, therefore; we do not get an out of range exception.

$ dotnet run
5
2

C# shuffle list

In the following example, we shuffle lists.

Program.cs
var rng = new Random();

var vals = new List<int> { 1, 2, 3, 4, 5, 6 };
var words = new List<string> { "sky", "blue", "war", "toy", "tick" };

Shuffle<int>(vals);
Shuffle<string>(words);

foreach (var e in vals)
{
    Console.Write($"{e} ");
}

Console.WriteLine("\n-----------------------");

foreach (var e in words)
{
    Console.Write($"{e} ");
}

Console.WriteLine();

void Shuffle<T>(IList<T> vals)
{
    int n = vals.Count;

    while (n > 1)
    {
        n--;
        int k = rng.Next(n + 1);

        T value = vals[k];

        vals[k] = vals[n];
        vals[n] = value;
    }
}

In the example, we create a generic Shuffle method which randomly rearranges the elements of a list.

$ dotnet run
2 1 3 4 6 5 
-----------------------
blue war sky tick toy 

In this tutorial we have generated random values in C# language.

Read C# tutorial or list all C# tutorials.