Search⌘ K
AI Features

Random Numbers and Probability

Explore how to generate random integers and decimals using C#'s Random.Shared class, simulate probabilities, shuffle collections, and understand the use of GUIDs for unique identification in applications. Learn when to use cryptographic random number generators to ensure security.

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 ...