Question
How can I generate a random integer in C#?
Short Answer
By the end of this page, you will understand how to generate random integers in C# using the Random class, how integer ranges work, and how to avoid common mistakes such as repeatedly creating Random objects or misunderstanding the upper bound.
Concept
In C#, random integers are commonly generated with the Random class from the .NET standard library.
The most common method is:
Random random = new Random();
int number = random.Next(1, 11);
This generates an integer from 1 up to but not including 11, so the possible results are 1 through 10.
Why this matters
Random numbers are used in many kinds of programs:
- games for dice rolls, enemies, and loot
- testing with sample data
- simulations and probability experiments
- shuffling items
- generating temporary values
Understanding how Random.Next() works is important because beginners often expect both range values to be included. In C#, the second argument is exclusive.
Key idea
Random does not create truly random numbers. It creates pseudo-random numbers, which means they appear random for most programming tasks.
For normal application logic, this is usually fine. If you need security-sensitive randomness, such as generating passwords or tokens, you should use a cryptographic API instead of Random.
Mental Model
Think of Random as a machine that gives you a number each time you press a button.
- The
Randomobject is the machine. Next()is the button.- The range you provide tells the machine which shelf of numbers it may choose from.
If you say Next(1, 11), you are telling the machine:
Give me one number starting at 1, but stop before 11.
So it can pick:
- 1
- 2
- 3
- ...
- 10
But never 11.
A useful way to remember it is:
- minimum is included
- maximum is excluded
Syntax and Examples
Basic syntax
Random random = new Random();
int value = random.Next();
This gives a non-negative random integer.
Generate a random integer within a range
Random random = new Random();
int number = random.Next(1, 11);
Console.WriteLine(number);
What this does
1is the minimum value11is the exclusive upper limit- possible results are
1to10
Generate a random integer from 0 to 9
Random random = new Random();
int digit = random.Next(0, 10);
Console.WriteLine(digit);
Generate a random integer with only an upper bound
Random random = new Random();
int number = random.Next(5);
Console.WriteLine(number);
Step by Step Execution
Consider this example:
Random random = new Random();
int roll = random.Next(1, 7);
Console.WriteLine(roll);
Step by step
-
Random random = new Random();- A new random number generator is created.
-
int roll = random.Next(1, 7);- The program asks for a number starting at
1and ending before7. - The possible results are
1, 2, 3, 4, 5, 6. - Suppose the generated value is
4.
- The program asks for a number starting at
-
Console.WriteLine(roll);- The value stored in
rollis printed. - Output would be:
- The value stored in
4
Another trace example
Random random = new Random();
a = random.Next(, );
b = random.Next(, );
Console.WriteLine();
Real World Use Cases
Random integers appear in many practical situations.
Games
- rolling dice
- picking a random enemy spawn point
- choosing random rewards
- shuffling card indices
Random random = new Random();
int damage = random.Next(5, 16);
Test data generation
Developers often generate fake ages, scores, or IDs for testing.
Random random = new Random();
int age = random.Next(18, 66);
Simulations
You can simulate events such as coin flips, lottery draws, or traffic behavior.
Random random = new Random();
int coin = random.Next(0, 2); // 0 or 1
Load balancing or sampling
A script might randomly choose one server, one message variation, or one item from a list.
Random random = new Random();
int serverIndex = random.Next(0, 3);
Educational and beginner projects
Real Codebase Usage
In real C# projects, developers usually do more than just call Next() once.
Reuse one Random instance
A common pattern is to keep one shared generator instead of creating a new one repeatedly.
private static readonly Random random = new Random();
This avoids repeated similar results caused by creating many instances too quickly.
Random selection from a collection
string[] colors = { "red", "green", "blue" };
string chosen = colors[random.Next(0, colors.Length)];
This pattern is common when choosing:
- a random item from a list
- a random test case
- a random default message
Guarding against empty collections
if (colors.Length == 0)
{
throw new InvalidOperationException("The collection is empty.");
}
string chosen = colors[random.Next(0, colors.Length)];
This is a good example of a guard clause.
Encapsulating random logic in a method
Common Mistakes
1. Expecting the upper bound to be included
Broken expectation:
Random random = new Random();
int number = random.Next(1, 10);
Many beginners expect 1 through 10, but this actually returns 1 through 9.
Fix
int number = random.Next(1, 11);
2. Creating Random repeatedly in a short time
Broken pattern:
for (int i = 0; i < 5; i++)
{
Random random = new Random();
Console.WriteLine(random.Next(1, 7));
}
This can produce repeated or poor-quality results because each object may be seeded similarly.
Fix
Random random = Random();
( i = ; i < ; i++)
{
Console.WriteLine(random.Next(, ));
}
Comparisons
| Approach | Example | Range behavior | Best use |
|---|---|---|---|
Next() | random.Next() | Non-negative integer | Any random integer when exact range does not matter |
Next(max) | random.Next(5) | 0 to max - 1 | Indexes, digits, list positions |
Next(min, max) | random.Next(1, 11) | min to max - 1 | Custom ranges such as dice rolls or ages |
vs cryptographic randomness
Cheat Sheet
Random random = new Random();
Main methods
random.Next(); // 0 or greater
random.Next(max); // 0 to max - 1
random.Next(min, max); // min to max - 1
Range rules
- lower bound is included
- upper bound is excluded
Examples
random.Next(5); // 0, 1, 2, 3, 4
random.Next(1, 7); // 1, 2, 3, 4, 5, 6
random.Next(10, 11); // always 10
Best practice
Random random = new Random();
// reuse this instance
Avoid
new Random(); // repeatedly inside loops
Use cryptographic randomness instead of Random for
- passwords
- reset tokens
- API keys
- security codes
FAQ
Why does random.Next(1, 10) never return 10?
Because the second argument is exclusive. random.Next(1, 10) returns values from 1 to 9.
How do I get a random number from 1 to 10 in C#?
Use:
random.Next(1, 11)
Should I create a new Random every time I need a number?
No. Usually you should create one Random object and reuse it.
What is the difference between Next(max) and Next(min, max)?
Next(max) starts at 0. Next(min, max) starts at min. In both cases, the upper bound is excluded.
Is Random truly random?
No. It is pseudo-random, which is good enough for many normal programming tasks.
Can I use Random for passwords or security tokens?
Mini Project
Description
Build a simple number guessing game in C#. The program should generate a random integer and let the user keep guessing until they find the correct number. This demonstrates how random integer generation works in a practical program and reinforces range handling, loops, and input parsing.
Goal
Create a console app that generates a random number from 1 to 20 and lets the user guess until they get it right.
Requirements
- Generate one random integer from 1 to 20.
- Reuse a single
Randomobject. - Ask the user to enter guesses in a loop.
- Tell the user whether the guess is too low, too high, or correct.
- Count how many guesses the user needed.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.