0
0
CsharpHow-ToBeginner · 3 min read

How to Generate Random Number in C# - Simple Guide

In C#, you generate random numbers using the Random class. Create an instance like var rnd = new Random(); and call rnd.Next() for integers or rnd.NextDouble() for decimals.
📐

Syntax

The Random class is used to generate random numbers. You create an object with new Random(). Then use methods like Next() to get a random integer or NextDouble() for a random decimal between 0 and 1.

  • Random rnd = new Random(); - creates a random number generator
  • rnd.Next() - returns a random integer
  • rnd.Next(min, max) - returns a random integer between min (inclusive) and max (exclusive)
  • rnd.NextDouble() - returns a random double between 0.0 and 1.0
csharp
Random rnd = new Random();
int number = rnd.Next(1, 10); // random number from 1 to 9
double decimalNumber = rnd.NextDouble(); // random decimal between 0.0 and 1.0
💻

Example

This example shows how to generate a random integer between 1 and 100 and a random decimal between 0 and 1. It prints both values to the console.

csharp
using System;

class Program
{
    static void Main()
    {
        Random rnd = new Random();
        int randomInt = rnd.Next(1, 101); // 1 to 100 inclusive
        double randomDouble = rnd.NextDouble(); // 0.0 to 1.0

        Console.WriteLine($"Random integer: {randomInt}");
        Console.WriteLine($"Random decimal: {randomDouble}");
    }
}
Output
Random integer: 57 Random decimal: 0.374829374
⚠️

Common Pitfalls

A common mistake is creating a new Random object inside a loop or repeatedly in a short time. This can cause the same random numbers to appear because Random uses the system clock as a seed.

To avoid this, create one Random instance and reuse it.

csharp
/* Wrong way: creates new Random each loop, may repeat numbers */
for (int i = 0; i < 5; i++)
{
    Random rnd = new Random();
    Console.WriteLine(rnd.Next(1, 10));
}

/* Right way: create Random once and reuse */
Random rnd = new Random();
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(rnd.Next(1, 10));
}
📊

Quick Reference

  • Random(): Creates a random number generator.
  • Next(): Returns a non-negative random integer.
  • Next(min, max): Returns a random integer between min (inclusive) and max (exclusive).
  • NextDouble(): Returns a random double between 0.0 and 1.0.

Key Takeaways

Use the Random class to generate random numbers in C#.
Create one Random instance and reuse it to avoid repeated values.
Use Next(min, max) for integers in a range and NextDouble() for decimals.
Random.Next(max) returns numbers from 0 up to max-1.
Avoid creating Random objects repeatedly in quick succession.