Search⌘ K

Fix the Trivial Problems

Explore methods to redesign C# random number generation by implementing thread-safe, cryptographically secure random integers and doubles. Understand how to address common problems with System.Random, improve randomness quality, and balance safety with performance.

In the previous lesson, we discussed the shortcomings of System.Random. In this lesson, we will begin redesigning the Random library.


First Attempt to Fixing Random

The first thing we want is two static methods, one that gives me an actually-random integer from 0 to Int32.MaxValue, and one that gives us a random double from 0.00.0 (inclusive) to 1.01.0 (exclusive). Not pseudo-random, but indistinguishable from a true random uniform distribution.

Here’s an attempt:

using CRNG = System.Security.Cryptography.RandomNumberGenerator;
public static class BetterRandom
{
  private static readonly ThreadLocal<CRNG> crng = new ThreadLocal<CRNG>(CRNG.Create);
  private static readonly ThreadLocal<byte[]> bytes =
    new
...