Random Numbers and Probability
Learn how to generate random integers, floating-point numbers, probabilities, and globally unique identities.
While the Math class handles precise, deterministic calculations, the Random class allows you to introduce unpredictability into your applications. This is essential for simulations, games, randomized testing, and generating temporary data.
Historically, developers often incorrectly instantiated a new Random object for every generation request. Creating multiple instances too quickly caused the underlying time-based seeds to match, resulting in identical number sequences.
Modern C# solves this by providing Random.Shared. This is a built-in, thread-safe instance of the Random class that is globally available. You should use Random.Shared for almost all standard random number generation.
Generating random integers
To generate random whole numbers, use the .Next() method. You can call this method with no arguments, one argument, or two arguments to control the range of the generated numbers.
The .Next(minValue, maxValue) method requires strict attention to boundary inclusiveness. The minValue is inclusive, but the maxValue is exclusive.