C# Number Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
In C#, you can generate random numbers using the Random
class, which generates pseudorandom numbers. However, if you need to generate cryptographically secure random numbers, you should use the System.Security.Cryptography
namespace.
Random random = new Random(); int randomNumber = random.Next();
In this example, the Random
class is used to generate a pseudorandom integer. The Next()
method generates a random integer.
using System.Security.Cryptography; ... RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider(); byte[] randomNumber = new byte[4]; cryptoProvider.GetBytes(randomNumber); int secureRandomNumber = BitConverter.ToInt32(randomNumber, 0);
In this example, the RNGCryptoServiceProvider
class is used to generate cryptographically secure random numbers. The GetBytes
method generates an array of bytes containing the random number, and the BitConverter.ToInt32
method converts the byte array to an integer.
Random random = new Random(); long randomNumber = ((long)random.Next() << 32) | random.Next();
In this example, the Random
class is used to generate a pseudorandom integer. The Next()
method generates a random integer. To generate a 64-bit integer, two random integers are generated and combined using the bitwise OR operator.
using System.Security.Cryptography; ... RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider(); byte[] randomNumber = new byte[4]; cryptoProvider.GetBytes(randomNumber); int secureRandomNumber = BitConverter.ToInt32(randomNumber, 0);
In this example, the RNGCryptoServiceProvider
class is used to generate cryptographically secure random integers. The GetBytes
method generates an array of bytes containing the random number, and the BitConverter.ToInt32
method converts the byte array to an integer. This method is similar to the example for generating secure random numbers, but only generates a 32-bit integer. If you need a 64-bit integer, you can use a similar method to the example for generating random Int64.
C# generate random number
Random random = new Random(); int randomNumber = random.Next();
Creating random integers in C#
Similar to generating a random number, but you can specify a range:
int randomInteger = random.Next(minValue, maxValue);
C# random number between 1 and 100
int randomNumber = random.Next(1, 101);
Generate random double in C#
double randomDouble = random.NextDouble();
Generate random long in C#
long randomLong = ((long)random.Next() << 32) | random.Next();
C# random number with specific seed
You can initialize Random
with a specific seed for reproducibility:
Random randomWithSeed = new Random(seed);
Creating random byte in C#
byte[] randomBytes = new byte[1]; random.NextBytes(randomBytes); byte randomByte = randomBytes[0];
C# random number without duplicates
You can shuffle a list of numbers and pick one at a time:
List<int> numbers = Enumerable.Range(minValue, maxValue - minValue + 1).ToList(); numbers.Shuffle(); // Implement a shuffle extension method int randomWithoutDuplicates = numbers[0];
Generate random boolean in C#
bool randomBoolean = random.Next(2) == 0;
C# random number with Gaussian distribution
Achieving true Gaussian distribution requires more advanced techniques, but you can use the Box-Muller transform:
double u1 = 1.0 - random.NextDouble(); double u2 = 1.0 - random.NextDouble(); double randomGaussian = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
Creating random Guid in C#
Guid randomGuid = Guid.NewGuid();
Generate random string in C#
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; string randomString = new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
Creating random DateTime in C#
DateTime startDate = new DateTime(2000, 1, 1); int range = (DateTime.Today - startDate).Days; DateTime randomDate = startDate.AddDays(random.Next(range));
C# random number with specified precision
double precision = 0.01; double randomWithPrecision = Math.Round(random.NextDouble() * (maxValue - minValue) + minValue, 2);
Generate random unique numbers in C#
You can use a HashSet to keep track of generated numbers and ensure uniqueness.
HashSet<int> uniqueNumbers = new HashSet<int>(); int uniqueRandomNumber; do { uniqueRandomNumber = random.Next(minValue, maxValue); } while (!uniqueNumbers.Add(uniqueRandomNumber));