Working with the Random class in C#

Rasheed K Mozaffar - May 12 '23 - - Dev Community

...
If you want to generate a basic random number, be it for a number guessing game or generating test data, you will need a way to generate the random numbers, and luckily, the Random class in C# provides the essentials for doing just that.

How does it work

To make use of the Random class, we need to create an instance of it, in its constructor goes something known as a seed value, this value serves a purpose for the random generator algorithm, the seed ultimately becomes the starting point for the random number sequence that the instance will generate. However, the seed value is optional, and honestly you should avoid providing one, because if the seed value is known, the random numbers can be guessed, which defeats the sole purpose of a random being a random here.

A question you may ask is, what would happen if we do not supply a seed value?

When that value isn't provided while creating the random class instance, it'll automatically use the system clock as a seed, and it's basically the moment at which the instance was created, I believe it's a very small number in like nano seconds or something, which isn't really that important, just know that when you supply a value, the produced random outcome could be guessed and that's not practical.

For demonstration purposes, I'll show you an example, the example code is written in a console app, keeping things simple as usual.


Random random = new Random(5);

for(int i = 0; i < 10; i++)
{
    Console.WriteLine(random.Next());
}

Enter fullscreen mode Exit fullscreen mode

Now I provided 5 as a seed value, I could've supplied any number that came to my mind, but that's not the interesting part, the code here is pretty basic, I'm just initializing a random instance and using a for loop to generate 10 Non-negative integers using the Next() method.
Now, if you do a dotnet run, you'll get 10 random numbers, however, running the app again and again will yield out the same result every single time, that's because I added that seed value while creating my random instance, you're now getting the same fixed numbers every time you're running the app, which doesn't seem any useful. For instance, if you're creating a random number guessing game, the random number once guessed, will be the exact answer every time, like say the correct answer is 88, no matter how many times you re run your game, the answer is 88.

Another situation is if you created 2 random instances at the same time, without supplying any seed value, because they'll use the system clock, and they both were created at an equivalent time, the random sequences they'll generate are going to be the same, so for that reason, always create a single instance, and use the Next method when you want a new random number.

The random numbers you'll get from the next method are going to be within an unspecified range, but what if you need something within a particular range? You can specify the bounds for your random number in the call for Next().

When calling the Next method, you can supply 2 arguments, the lower and upper bounds, or just the upper bound (In this case the lower bound will default to 0). You got to pay attention to the fact that the upper bound isn't inclusive, like if you want your higher bound to be 10, you will need to do this:

Random random = new Random();

int randomNumber1 = random.Next(0, 10); //Wrong
int randomNumber2 = random.Next(0, 11); //Correct

Enter fullscreen mode Exit fullscreen mode

But what if I want to generate random numbers with fractions, like doubles?

Well, Random got you covered, instead of calling Next(), you can call NextDouble(). This method will generate a random double between 0 and 1, the upper bound is exclusive so the highest number could be 0.999...
But that's limited, If you want a number that's not only between 0 and 1, you can multiply by it, like this:


Random random = new Random();

//This will generate a double between 0 and 10.9...
Console.WriteLine(random.NextDouble() * 11);


Enter fullscreen mode Exit fullscreen mode

Again, remember that the upper bound isn't inclusive and thus I'm multiplying by 11 and not 10, now we can get random doubles from 0 up to 10.999...

✅ End reached

I think this post was quite concise and short, but I suppose it's a nice idea to recall such a concept that we usually learn at the beginning and then ignore for considerably a long time, overall, even if the chances are low for actually using randoms in your projects, it's still something viable to be aware of as they might come in handy at a certain time.
...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .