I’m trying to generate a C# random number and want to make sure I do it correctly. I need an integer between two values, say between 1 and 100.
What’s the right way to create a random number generator in C# and use it to get values within a given range? A quick example would be helpful!
The most straightforward way is using Random.Next(min, max)
, which returns an integer from min
(inclusive) to max
(exclusive). So if you want a number between 1 and 100 including 100:
var rnd = new Random();
int number = rnd.Next(1, 101); // Upper bound is exclusive
Just be careful if you’re calling this repeatedly or in a tight loop. It’s best to create the Random
instance once and reuse it. Creating new instances quickly can lead to the same number being generated because of time-based seeding.
If you’re working in a multithreaded app (like a web API), Random might not be thread-safe and could produce weird results under load.
That’s where System.Security.Cryptography.RandomNumberGenerator
(or the newer RandomNumberGenerator.GetInt32
) really shines:
using System.Security.Cryptography;
int number = RandomNumberGenerator.GetInt32(1, 101);
This not only avoids threading issues but also provides cryptographic-grade randomness, which is overkill for basic games but perfect if you’re doing anything security-related or concurrent.