user57508
user57508

Reputation:

Random.Next() gives me the same value

We have this class here:

public static class Helper
{
    private static readonly Random Random = new Random();
    public static int GetRandomId()
    {
        return Random.Next(int.MinValue, 0);
    }
}

At some point calling .GetRandomId of Helper gives us the same integer - Why and how do avoid/fix this?

Note:
The field Random is a singleton-instance, and this behaviour does not occur in a loop (actually it doesn't even matter how much time there's between the calls).

To be even more specific:
At some point the random-machine returns only one value, regardless of the amount of calls! It's not about the likeliness, uniqueness ... - I think that I have (with this implementation) broken my random-instance ... how come?

Upvotes: 1

Views: 794

Answers (2)

Adam
Adam

Reputation: 16199

Well it is random, it doesn't remember what it has done in the past.

Keep a list of already given numbers and check it hasn't already been given before returning.

More details on why it also repeats more often than you would expect can be found here: http://csharpindepth.com/Articles/Chapter12/Random.aspx

Upvotes: 1

Andrew Kennan
Andrew Kennan

Reputation: 14157

The Next method returns a pseudo-random number between int.MinValue and 0. It does not guarantee the numbers will be unique. What do you think happens if you call Random.Next(0,10) 11 times?

To prevent duplicates you'll need to keep track of which Ids have been issued.

Alternatively, is there any need for the Ids to be in a random order? Could you just use an incrementing int to generate Ids?

Upvotes: 4

Related Questions