ZetCode

C# Random

last modified November 6, 2026

In this article we show how to generate random values in C# with the built-in Random class. We generate numbers in a range, reproduce sequences with a seed, pick and shuffle elements, create random strings, and produce secure random values for passwords and tokens.

Random number generators

A random number generator (RNG) produces a sequence of values that shows no discernible pattern. Hardware generators measure physical noise and are considered truly random. Pseudo-random number generators (PRNG) compute the values with an algorithm. Their output looks random, but it is fully determined by the initial state, called the seed. Given the same seed, a PRNG produces the same sequence again.

The Random class is a fast PRNG for simulations, games, sampling, and tests. It is not suitable for security. Passwords, keys, and tokens must be produced by a cryptographically secure generator, which in .NET is the RandomNumberGenerator class.

Note: In modern .NET, new Random() without a seed uses the xoshiro256** algorithm (xoshiro128** in 32-bit processes) seeded from the operating system's entropy source, so separate instances created at the same moment produce different sequences. new Random(seed) keeps the older subtractive generator from .NET Framework for compatibility, so that programs relying on a seed keep producing the same sequences. Microsoft does not guarantee this across versions, so do not persist data that depends on it.

C# random numbers

The first example generates random numbers of various types.

Program.cs
var rnd = new Random();

Console.WriteLine(rnd.Next());
Console.WriteLine(rnd.NextInt64());
Console.WriteLine(rnd.NextDouble());
Console.WriteLine(rnd.NextSingle());

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

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

We create a generator and call its basic methods.

Console.WriteLine(rnd.Next());
Console.WriteLine(rnd.NextInt64());

The Next method returns a non-negative int smaller than int.MaxValue; NextInt64 returns a non-negative long.

Console.WriteLine(rnd.NextDouble());
Console.WriteLine(rnd.NextSingle());

The NextDouble and NextSingle methods return a floating-point number greater than or equal to 0.0 and less than 1.0.

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

The NextBytes method fills an array or a span with random bytes.

$ dotnet run
1530430838
2274868664257410525
0.7763099987297246
0.43931973
210 26 185 29 255 65 188 177

Random numbers in a range

The Next and NextInt64 methods have overloads with bounds. The lower bound is inclusive and the upper bound is exclusive.

Program.cs
var rnd = Random.Shared;

Console.WriteLine(rnd.Next(5));
Console.WriteLine(rnd.Next(10, 21));
Console.WriteLine(rnd.Next(-5, 6));
Console.WriteLine(rnd.NextInt64(1_000_000_000_000, 10_000_000_000_000));

double min = 1.5;
double max = 2.5;
double d = min + rnd.NextDouble() * (max - min);
Console.WriteLine($"{d:F4}");

int[] rolls = [.. Enumerable.Range(0, 10).Select(_ => rnd.Next(1, 7))];
Console.WriteLine(string.Join(" ", rolls));

We generate numbers in several ranges and simulate ten rolls of a die.

var rnd = Random.Shared;

The Random.Shared property returns a thread-safe instance shared by the whole application. It is the simplest way to get random numbers without creating and storing our own Random object. An ordinary Random instance must not be used from several threads at once.

Console.WriteLine(rnd.Next(10, 21));
Console.WriteLine(rnd.Next(-5, 6));

Since the upper bound is exclusive, we pass 21 to include 20 and 6 to include 5. The range may contain negative numbers.

double d = min + rnd.NextDouble() * (max - min);

There is no overload with bounds for doubles. We scale the value from NextDouble to the desired interval.

int[] rolls = [.. Enumerable.Range(0, 10).Select(_ => rnd.Next(1, 7))];

A die roll is a number from 1 to 6, so the upper bound is 7.

$ dotnet run
4
18
-4
1080657413610
1.7031
6 6 5 4 1 6 2 3 4 2

The seed

Passing a seed to the constructor makes the sequence reproducible. This is useful in tests, simulations that must be repeated, and procedurally generated content.

Program.cs
var r1 = new Random(42);
var r2 = new Random(42);
var r3 = new Random(43);

for (int i = 0; i < 6; i++)
{
    Console.WriteLine($"{r1.Next(100),3} {r2.Next(100),3} {r3.Next(100),3}");
}

We create two generators with the same seed and one with a different seed.

var r1 = new Random(42);
var r2 = new Random(42);
var r3 = new Random(43);

The first two columns are always identical. The output of this program is the same on every run.

$ dotnet run
 66  66  19
 14  14  43
 12  12  82
 52  52  73
 16  16  61
 26  26  13

Distribution of random numbers

The numbers produced by Next are uniformly distributed: each value in the range is equally likely. We verify it by rolling a die 60,000 times.

Program.cs
var rnd = new Random(7);
var counts = new int[7];

const int rolls = 60_000;

for (int i = 0; i < rolls; i++)
{
    counts[rnd.Next(1, 7)]++;
}

for (int face = 1; face <= 6; face++)
{
    double pct = 100.0 * counts[face] / rolls;
    Console.WriteLine($"{face}: {counts[face],6} {pct,6:F2}% {new string('#', counts[face] / 500)}");
}

We count the occurrences of each face and print a simple histogram.

counts[rnd.Next(1, 7)]++;

The roll is used directly as an index into the array of counters; index 0 is not used.

Each face appears close to 10,000 times, which is one sixth (16.67%) of the rolls. Thanks to the fixed seed, the counts are the same on every run.

$ dotnet run
1:  10128  16.88% ####################
2:  10058  16.76% ####################
3:   9911  16.52% ###################
4:  10098  16.83% ####################
5:   9951  16.59% ###################
6:   9854  16.42% ###################

Picking random elements

To pick a random element, we generate a random index. The GetItems method picks several elements at once.

Program.cs
var rnd = Random.Shared;

List<string> words = ["sky", "blue", "war", "toy", "tick", "cloud", "pen"];

string w = words[rnd.Next(words.Count)];
Console.WriteLine(w);

string[] picks = rnd.GetItems(words.ToArray(), 5);
Console.WriteLine(string.Join(", ", picks));

string[] sample = [.. words.OrderBy(_ => rnd.Next()).Take(3)];
Console.WriteLine(string.Join(", ", sample));

We pick one word, five words with repetition, and three distinct words.

string w = words[rnd.Next(words.Count)];

The upper bound of Next is exclusive, so the index is always valid.

string[] picks = rnd.GetItems(words.ToArray(), 5);

The GetItems method returns an array of randomly chosen elements. The elements are picked independently, so the same element can appear more than once.

string[] sample = [.. words.OrderBy(_ => rnd.Next()).Take(3)];

To get distinct elements, we order the list by random keys and take the first three. For large collections, shuffling a copy is more efficient.

$ dotnet run
cloud
war, blue, blue, toy, tick
cloud, pen, sky

Shuffling

The Shuffle method randomly reorders an array or a span in place. It uses the Fisher-Yates algorithm, where each permutation is equally likely.

Program.cs
using System.Runtime.InteropServices;

var rnd = Random.Shared;

int[] vals = [1, 2, 3, 4, 5, 6, 7, 8];
rnd.Shuffle(vals);
Console.WriteLine(string.Join(" ", vals));

List<string> words = ["sky", "blue", "war", "toy", "tick"];
rnd.Shuffle(CollectionsMarshal.AsSpan(words));
Console.WriteLine(string.Join(" ", words));

char[] letters = [.. "abcdefgh"];
FisherYates(letters);
Console.WriteLine(new string(letters));

void FisherYates<T>(IList<T> items)
{
    for (int n = items.Count - 1; n > 0; n--)
    {
        int k = rnd.Next(n + 1);
        (items[n], items[k]) = (items[k], items[n]);
    }
}

We shuffle an array, a list, and an array of characters with our own implementation of the algorithm.

rnd.Shuffle(CollectionsMarshal.AsSpan(words));

There is no Shuffle overload for List<T>. The CollectionsMarshal.AsSpan method gives us a span over the list's internal array, so the list is shuffled in place. The list must not be modified in other ways while the span is in use.

for (int n = items.Count - 1; n > 0; n--)
{
    int k = rnd.Next(n + 1);
    (items[n], items[k]) = (items[k], items[n]);
}

The Fisher-Yates shuffle goes from the last element to the first and swaps each element with a random element at the same or a lower position. The swapping is done with a tuple.

$ dotnet run
8 7 5 2 3 1 6 4
war blue sky toy tick
bfedgcah

Random strings

Since .NET 10, the GetString and GetHexString methods generate random strings directly.

Program.cs
var rnd = Random.Shared;

const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

string s1 = rnd.GetString(chars, 12);
Console.WriteLine(s1);

string s2 = rnd.GetHexString(16);
Console.WriteLine(s2);

string s3 = rnd.GetHexString(16, lowercase: true);
Console.WriteLine(s3);

char[] buf = new char[12];

for (int i = 0; i < buf.Length; i++)
{
    buf[i] = chars[rnd.Next(chars.Length)];
}

Console.WriteLine(new string(buf));

We generate an alphanumeric string and two hexadecimal strings, and build an alphanumeric string manually.

string s1 = rnd.GetString(chars, 12);

The GetString method returns a string of the given length whose characters are picked from the provided set.

string s3 = rnd.GetHexString(16, lowercase: true);

The GetHexString method returns hexadecimal digits, in upper case by default.

for (int i = 0; i < buf.Length; i++)
{
    buf[i] = chars[rnd.Next(chars.Length)];
}

On older .NET versions, we pick the characters one by one.

$ dotnet run
pRRPVMR1uBxZ
00447F64A67553C0
1afe7033823fd58d
bHnn5BGeWveR

Random booleans and enum values

Random booleans and enum values are derived from random integers.

Program.cs
var rnd = Random.Shared;

bool b = rnd.Next(2) == 0;
Console.WriteLine(b);

bool rare = rnd.NextDouble() < 0.1;
Console.WriteLine(rare);

Color[] colors = Enum.GetValues<Color>();
Color c = colors[rnd.Next(colors.Length)];
Console.WriteLine(c);

Color[] some = rnd.GetItems(colors, 4);
Console.WriteLine(string.Join(", ", some));

enum Color { Red, Green, Blue, Yellow }

We generate two booleans with different probabilities and pick random colors.

bool rare = rnd.NextDouble() < 0.1;

This boolean is true with a probability of 10%.

Color[] colors = Enum.GetValues<Color>();
Color c = colors[rnd.Next(colors.Length)];

The generic Enum.GetValues<T> method returns the members of the enumeration as a typed array, from which we pick a random one.

enum Color { Red, Green, Blue, Yellow }

In a program with top-level statements, type declarations must come after the statements.

$ dotnet run
False
False
Yellow
Green, Green, Blue, Green

Secure random values

The RandomNumberGenerator class from the System.Security.Cryptography namespace produces cryptographically secure random values. Its static methods mirror the Random API.

Program.cs
using System.Security.Cryptography;

int pin = RandomNumberGenerator.GetInt32(0, 10_000);
Console.WriteLine($"{pin:D4}");

string token = RandomNumberGenerator.GetHexString(32, lowercase: true);
Console.WriteLine(token);

const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%";
string password = RandomNumberGenerator.GetString(chars, 16);
Console.WriteLine(password);

byte[] key = RandomNumberGenerator.GetBytes(16);
Console.WriteLine(Convert.ToBase64String(key));

We generate a PIN, a hexadecimal token, a password, and a key encoded in Base64.

int pin = RandomNumberGenerator.GetInt32(0, 10_000);

The GetInt32 method returns a number from the range, with an exclusive upper bound. The PIN is padded to four digits.

string password = RandomNumberGenerator.GetString(chars, 16);

The character set omits similar-looking characters such as 0, O, 1, and l.

byte[] key = RandomNumberGenerator.GetBytes(16);

The GetBytes method returns an array of random bytes, here a 128-bit key.

$ dotnet run
9937
34211b362249bf88b6d1f6597356c19f
qGe7sYZ8xadQ4HoM
j4xA0YNkIOdrUpjWLfMBMA==

Source

Random class

In this article we have generated random values in C# with the Random and RandomNumberGenerator classes.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.