Question

How to Generate a Random Integer in C#

csharprandom

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 Random object 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
Take Quiz

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

  • 1 is the minimum value
  • 11 is the exclusive upper limit
  • possible results are 1 to 10

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);

This returns a number from 0 to 4.

Reusing the same Random object

A better pattern is to create one Random object and reuse it:

Random random = new Random();

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(random.Next(1, 7));
}

This prints 5 random integers from 1 to 6, similar to rolling a die 5 times.

Step by Step Execution

Consider this example:

Random random = new Random();
int roll = random.Next(1, 7);
Console.WriteLine(roll);

Step by step

  1. Random random = new Random();

    • A new random number generator is created.
  2. int roll = random.Next(1, 7);

    • The program asks for a number starting at 1 and ending before 7.
    • The possible results are 1, 2, 3, 4, 5, 6.
    • Suppose the generated value is 4.
  3. Console.WriteLine(roll);

    • The value stored in roll is printed.
    • Output would be:
4

Another trace example

Random random = new Random();

int a = random.Next(0, 3);
int b = random.Next(0, 3);

Console.WriteLine($"a = {a}, b = {b}");

Possible execution:

  • a becomes 2
  • b becomes 0
  • output:
a = 2, b = 0

Each call to Next() asks the same generator for another value.

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

  • guessing games
  • quiz apps that randomize question order
  • random password character selection using indexes
  • simple procedural content generators
Take Quiz

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

public static int RollDie(Random random)
{
    return random.Next(1, 7);
}

This makes code easier to test and reuse.

Validation patterns

If user input defines a random range, validate it first:

if (min >= max)
{
    throw new ArgumentException("min must be less than max");
}

int value = random.Next(min, max);

Security-sensitive cases

In production systems, developers do not use Random for:

  • password reset tokens
  • API keys
  • authentication codes
  • cryptographic secrets

For those tasks, use cryptographically secure randomness APIs instead.

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 = new Random();

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(random.Next(1, 7));
}

3. Using Random for passwords or security tokens

Broken idea:

Random random = new Random();
int code = random.Next(100000, 999999);

This may look random, but Random is not suitable for security-sensitive values.

Fix

Use a cryptographic random API when security matters.

4. Passing invalid bounds

Broken code:

Random random = new Random();
int number = random.Next(10, 5);

This causes an error because the minimum must be less than the maximum.

Fix

int min = 5;
int max = 10;
int number = random.Next(min, max);

5. Forgetting that Next(max) starts at 0

Random random = new Random();
int number = random.Next(5);

This gives 0 to 4, not 1 to 5.

Fix

int number = random.Next(1, 6);

Comparisons

ApproachExampleRange behaviorBest use
Next()random.Next()Non-negative integerAny random integer when exact range does not matter
Next(max)random.Next(5)0 to max - 1Indexes, digits, list positions
Next(min, max)random.Next(1, 11)min to max - 1Custom ranges such as dice rolls or ages

Random vs cryptographic randomness

ToolUse caseSuitable for security?
RandomGames, simulations, sample dataNo
Cryptographic random APITokens, passwords, secure codesYes

Next(max) vs Next(min, max)

MethodExampleOutput
Next(10)random.Next(10)0 to 9
Next(1, 10)random.Next(1, 10)1 to 9
Next(1, 11)random.Next(1, 11)1 to 10
Take Quiz

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?

No. Use a cryptographically secure API for anything related to security.

How do I pick a random item from an array?

Use a random index:

string[] items = { "A", "B", "C" };
string item = items[random.Next(0, items.Length)];
Take Quiz

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 Random object.
  • 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.
Take Quiz

Keep learning

Related questions

View more