C# Reference ยท Numbers and Math
C# Random class
Reference for the C# Random class: Next, NextDouble, Random.Shared, seeds for repeatable sequences, shuffling and why it is not for security.
System.Random produces pseudo-random numbers: a sequence that looks random but is computed from a starting value, the seed. Use it for games, simulations, sampling, shuffling and test data. Do not use it for passwords, tokens or anything an attacker could benefit from predicting; use RandomNumberGenerator for that.
new Random() seeds itself from the system, so every run differs. new Random(seed) always yields the same sequence for the same seed on the same runtime, which is perfect for repeatable tests. Since .NET 6 the static property Random.Shared is a ready-made, thread-safe instance.
int roll = Random.Shared.Next(1, 7); // 1 to 6 double chance = Random.Shared.NextDouble(); // [0.0, 1.0)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public Random() public Random(int seed) public static Random Shared { get; } public virtual int Next() public virtual int Next(int maxValue) public virtual int Next(int minValue, int maxValue) public virtual long NextInt64() public virtual long NextInt64(long minValue, long maxValue) public virtual double NextDouble() public virtual float NextSingle() public virtual void NextBytes(byte[] buffer) public void Shuffle<T>(T[] values) // .NET 8+, also Span<T> public T[] GetItems<T>(T[] choices, int length) // .NET 8+, also ReadOnlySpan<T>
| Name | Description |
|---|---|
seed |
Starting value for a repeatable sequence. |
minValue |
Inclusive lower bound. |
maxValue |
Exclusive upper bound. |
buffer |
Receives random bytes. |
Returns: Next() is in [0, int.MaxValue). Next(max) is in [0, max). Next(min, max) is in [min, max). NextDouble() and NextSingle() are in [0, 1).
Errors: ArgumentOutOfRangeException if maxValue is negative or minValue > maxValue. Next(5, 5) returns 5 (an empty range gives the minimum).
Usage notes
- Upper bounds are exclusive. A die roll is
Next(1, 7), notNext(1, 6). This is the most common mistake. - Do not create generators in a loop. Two instances created back to back with the default constructor are seeded independently in modern .NET, but creating many wastes time. Keep one instance or use
Random.Shared. - Thread safety. Instances you create are not thread-safe; concurrent use can corrupt state and return zeros.
Random.Sharedis thread-safe. - Seeded sequences are not portable. With a seed,
Randomuses a legacy algorithm for compatibility, and the exact values may differ between .NET versions or other languages. Rely on repeatability within one runtime, not on specific numbers. - Not cryptographically secure. Anyone who observes enough output can predict the rest. Use
RandomNumberGeneratorfor secrets. - Modulo bias.
Next() % nslightly favors small numbers. UseNext(n), which handles ranges correctly. - Shuffling by hand. Sorting by
Random.Next()is biased and slow. UseRandom.Shuffleor write a Fisher-Yates loop. - Unit tests. Inject a
Randomseeded with a constant so tests are repeatable.
Related
num-randomnumbergeneratornum-mathtype-guidfor unique IDs- Tutorial: Math and numbers