Darko Darko - 3 months ago 11
C# Question

C# Generate random numbers, while using library, that use internal Random instance

In order to ensure different random numbers, you should use just one instance of a

Random
class, as suggested in the answers here, here and here.

In my library, I need the random numbers, so I created a class
Randomizer
, which provides methods, that returns random numbers using single
Random
instance. Here is a fragment of the
Randomizer
code:

class Randomizer
{
private Randomizer() { }
public static Randomizer Instance { get; } = new Randomizer();

private static readonly Random random = new Random();
private static readonly object syncLock = new object();

public int Next(int minValue, int maxValue)
{
lock(syncLock)
{
return random.Next(minValue, maxValue);
}
}

// rest of code
}


Now, what if a user of my library also need the random numbers? Should I make my
Randomizer
class public and specify in the documentation of the library, that users should use my
Randomizer
class in order to generate random numbers?

Answer

In order to ensure different random numbers, you should use just one instance of a Random class

That's not quite right. It's perfectly fine to create multiple instances of Random as long as you don't initialise them all in a tight loop (since they are seeded by the current time, so you want the current time to be different for each at the point of instantiation).

As you're creating a static class that just creates one Random object and reuses it, that's fine. It's theoretically possible that a caller of your library could create their own static Random that gets created at the same time, so their generator gets the same seed as yours and so the same sequence of random numbers. That probably won't happen because of the time it takes to create the static classes. It also probably won't matter anyway unless there's a reason why correlation matters between the caller's sequence and yours.