Random Number Generation in C#: From Beginner to Pro (Solving the Top Stack Overflow Question)

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Generate a Random Integer in C#: Let's Figure It Out Once and For All

\n

The question of random number generation is one of the most popular on Stack Overflow. It seems simple, right? But in practice, even experienced C# developers make classic mistakes: getting the same values on every run, encountering non-random sequences, or forgetting about thread safety. Today, we'll finally figure out how to properly generate random integers in C# and answer all the "whys" from that top Stack Overflow thread.

\n\n

This article is your chance to stop copying code from the internet and start understanding what's really happening under the hood of System.Random. Let's go!

\n\n

Why Do Beginners Get the Same Number Over and Over?

\n

The most common question: "I create a Random and always get the same number!". Let's look at a typical trap code:

\n\n
// ❌ BAD EXAMPLE\nfor (int i = 0; i < 5; i++)\n{\n    Random rnd = new Random();\n    Console.WriteLine(rnd.Next(1, 100));\n}\n
\n\n

What will this code output? With 99% probability — five identical numbers. Why? Because Random uses the system clock for initialization (seed). When you create multiple Random instances in quick succession, they get the same seed, and consequently generate an identical sequence.

\n\n

The correct solution is to create one Random instance and reuse it:

\n\n
// ✅ CORRECT EXAMPLE\nRandom rnd = new Random();\nfor (int i = 0; i < 5; i++)\n{\n    Console.WriteLine(rnd.Next(1, 100));\n}\n
\n\n

Now each number will be different. Simple rule: one Random per execution thread.

\n\n

Random.Next(): Three Ways to Get a Random Integer

\n

The System.Random class offers three overloads of the Next() method. Let's look at each with examples:

\n\n

1. Random.Next() — No Parameters

\n

Returns a non-negative integer in the range from 0 to Int32.MaxValue - 1. That is, from 0 to 2,147,483,646.

\n
Random rnd = new Random();\nint anyNumber = rnd.Next();\nConsole.WriteLine(anyNumber); // Example: 1789034215\n
\n\n

2. Random.Next(Int32) — With Upper Bound

\n

Returns a number from 0 (inclusive) to the specified maximum (exclusive).

\n
int dice = rnd.Next(7); // 0, 1, 2, 3, 4, 5, or 6\nConsole.WriteLine(dice);\n
\n\n

3. Random.Next(Int32, Int32) — Range [min, max)

\n

The most popular option for generating a random integer in C# within a given range.

\n
// Random number from 1 to 100 (inclusive)\nint score = rnd.Next(1, 101);\nConsole.WriteLine(score);\n
\n\n

Important to remember: the upper bound is exclusive. To get a number from 1 to 6 (like on a die), write Next(1, 7).

\n\n

Top 3 Mistakes When Working with Random in C#

\n

Based on real questions from Stack Overflow C# random, let's highlight the most common pitfalls:

\n\n
    \n
  • Mistake #1: Creating a new Random in a loop. We've already covered this — it leads to identical numbers. Solution: move new Random() outside the loop.
  • \n
  • Mistake #2: Random is not thread-safe. If multiple threads use a single Random instance without synchronization, errors and zero values can occur. Use lock or ThreadLocal<Random>.
  • \n
  • Mistake #3: Using Random for passwords or tokens. System.Random is a pseudo-random generator. It's predictable! For security, you need System.Security.Cryptography.RandomNumberGenerator.
  • \n
\n\n

How to Generate Cryptographically Secure Random Numbers?

Blogs

Book Recommendations