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?
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?