Replayable randomness in C# using a fixed Random seed

Posted: (EET/GMT+2)

 

When testing systems with random input data, it can be useful to reproduce the exact same sequence of values later.

The C# language allows this by using a fixed seed when creating a Random instance. The same seed always produces the same pseudo-random sequence.

Example:

int seed = 12345;
Random rnd = new(seed);

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(rnd.Next(0, 100));
}

If you run this code multiple times, the output will always be the same.

This is useful for:

  • Reproducing bugs found during randomized testing.
  • Generating deterministic test datasets.
  • Re-running simulations with identical inputs.

If a test fails, logging the random seed makes it easy to replay the scenario later:

int seed = Environment.TickCount;
Console.WriteLine($"Seed: {seed}");

Random rnd = new(seed);

You can then rerun the test with the printed seed value.

Note that Random is not intended for cryptographic use. It is designed for deterministic pseudo-random sequences, which makes it well suited for repeatable testing.