Random Number Generation in C# – Methods and Examples

c++random

I have been writing some C# code for a training exercise, in which I had to create an array of random rectangles.

Problem being that the rectangle being produced by my GetRandomRectangle function was always the same.
I was using System.Random to generate the coordinates for the rectangle.

I've realised that it was because the Random object was beign created with the default constructor, and so had the same seed. I've modified it to get a different seed for each rectangle now, and it works fine.

The question is – how does it decide on the 'default seed'? I've noticed that it doesn't seem to change over time either, a rectangle created with seed 2 will always be given the same dimensions.

It's probably something that I could Google, but it's nice to hear opinions and info from you guys as well.

Thanks 🙂

Best Answer

The default seed is taken from the system clock.

I'm guessing that your GetRandomRectangle method was being called in quick succession and instantating a new instance of Random each time. When you do this, each instance of Random will take the same seed from the system clock, which is why your method created the same rectangle each time.

One solution is to create one instance of Random and pass that into your method:

Random rng = new Random();

Rectangle foo = GetRandomRectangle(rng);
Rectangle bar = GetRandomRectangle(rng);
Rectangle baz = GetRandomRectangle(rng);

// ...

public Rectangle GetRandomRectangle(Random rng)
{
    // create the rectangle using rng
}