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.