Back to Home

C# Random Number Guide: Random.Shared, Random.Next, and RandomNumberGenerator

Use Random for everyday pseudo-random values in apps and games. Use RandomNumberGenerator when you need cryptographically strong randomness.

Random.Shared and Random.Next

C# Example Code
int value = Random.Shared.Next(1, 101);
Console.WriteLine(value);

Random.Shared is a shared instance that is convenient when you need a simple random number generator without creating a new object each time.

Generate integers and ranges

C# Example Code
Random random = new();
Console.WriteLine(random.Next(10));
Console.WriteLine(random.Next(100, 200));
Console.WriteLine(random.NextInt64(1_000_000_000));

Cryptographic randomness

C# Example Code
byte[] bytes = new byte[16];
RandomNumberGenerator.Fill(bytes);
Console.WriteLine(Convert.ToHexString(bytes));

FAQ

Should I create a new Random every time?

No. Repeatedly creating Random instances can produce poor or repeated sequences.

When should I use RandomNumberGenerator?

Use it for passwords, tokens, nonces, and other security-sensitive values.

Take It Further

Concurrency in C# Cookbook book cover

Struggling with async/await? The definitive recipe book for every concurrency pattern in .NET.

Concurrency in C# Cookbook — 2nd Edition · Stephen Cleary

Get it on Amazon →

As an Amazon Associate I earn from qualifying purchases.