When tasked with generating Random numbers, some folks use a static method such as that shown below:

Code Snippet
  1. static Random rn = new Random();
  2. static int ReturnNextRandom(int maxIndex)
  3. {
  4.   return rn.Next(maxIndex);
  5. }

 

One of the reasons is that they want to keep the same, common instance of the Random Generator (Random class in C#). While this makes sense, there is no reason to stick to static methods – and be able to not do an instance method. The code below shows a way to use an OO approach – define a RandomGenerator class – which does exactly the same thing as the static method above.

Code Snippet
  1. interface IRandomGenerator
  2.     {
  3.         int ReturnNextRandom(int maxIndex);
  4.     }
  5.  
  6.     class RandomGenerator : IRandomGenerator
  7.     {
  8.         private static Random _rnd = new Random();
  9.         private static object _lock = new object();
  10.  
  11.         public int ReturnNextRandom(int maxIndex)
  12.         {
  13.             return Next(maxIndex);
  14.         }
  15.  
  16.         private int Next(int maxIndex)
  17.         {
  18.             lock (_lock)
  19.             {
  20.                return _rnd.Next(maxIndex);
  21.             }
  22.         }
  23.     }

Full Source Code

Download Source Code RandomGenerator

 

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.