Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend functions to Random class

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.

like image 964
Darf Zon Avatar asked Nov 01 '25 14:11

Darf Zon


1 Answers

You need to use the singleton pattern (See Implementing Singleton in C# on MSDN)

public class RandomSingleton
{
   private static Random instance;

   private RandomSingleton() {}

   public static Random Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Randon();
         }
         return instance;
      }
   }
}

You can then access the same instance of Random in your code anywhere as follows:

RandomSingleton.Instance.NextInt(24);

Please note that there is no need to re-seed this Random instance, because all your code will be using the same instance, hence you will not see repeated numbers.

like image 150
ColinE Avatar answered Nov 04 '25 05:11

ColinE