I’m trying to extend the functions from a Random class.
public static class RandomExtensions
{
public static void NextEven(this Random rnd, int min, int max)
{
// ...
}
public static void ReseedRandomNumberGenerator(this Random rnd, int? seed = null)
{
rnd = seed.HasValue ? new Random(seed.Value) : new Random();
}
}
But my doubt is the second function ReseedRandomNumberGenerator. I need something where many classes can interacts a Random class, but all those classes should have the same instance.
Suposse that I invoke ReseedRandom… it’s possible than the others classes should refresh or updated the new seed?
public class A()
{
protected Random Random = new Random();
}
public class B()
{
protected Random Random = new Random();
}
I know that this don’t work. Maybe I need a static property, I’m not sure.
You need to use the singleton pattern (See Implementing Singleton in C# on MSDN)
You can then access the same instance of Random in your code anywhere as follows:
Please note that there is no need to re-seed this
Randominstance, because all your code will be using the same instance, hence you will not see repeated numbers.