How to generate random numbers in C#
In C#, you can generate random numbers using the Random class. For better randomness in .NET 6+, use Random.Shared which is thread-safe and more efficient.
The Next() method generates integers within a specified range. The upper bound is exclusive, meaning Next(1, 7) generates numbers from 1 to 6.
For cryptographically secure random numbers, use RandomNumberGenerator from System.Security.Cryptography.
C# Example Code
using System;
public class RandomNumbers
{
public static void Main(string[] args)
{
// .NET 6+ recommended approach
int randomNumber = Random.Shared.Next(1, 101); // 1 to 100
Console.WriteLine($"Random number (1-100): {randomNumber}");
// Generate random number in range
int diceRoll = Random.Shared.Next(1, 7); // 1 to 6
Console.WriteLine($"Dice roll: {diceRoll}");
// Generate random double (0.0 to 1.0)
double randomDouble = Random.Shared.NextDouble();
Console.WriteLine($"Random double: {randomDouble:F4}");
// Legacy approach (pre-.NET 6)
Random random = new Random();
int legacyRandom = random.Next(1, 11); // 1 to 10
Console.WriteLine($"Legacy random: {legacyRandom}");
// Generate multiple random numbers
Console.WriteLine("\nFive random numbers:");
for (int i = 0; i < 5; i++)
{
Console.WriteLine(Random.Shared.Next(1, 101));
}
// Random boolean
bool coinFlip = Random.Shared.Next(2) == 0;
Console.WriteLine($"\nCoin flip: {(coinFlip ? "Heads" : "Tails")}");
}
}