Search code examples
c#randomsavegenerated

How to save values generated from Random.Next method C#


I bumped into a method for generating different values with the Random.Next() method in C#

Here's the code:

 private static readonly Random random = new Random();
 private static readonly object syncLock = new object();
 public static int RandomNumber(int min, int max)
 {
     lock(syncLock) { // synchronize
         return random.Next(min, max);
     }
 }

My question is how can I save each of these values every time create new instance with them and use them for each object separately

e.g

 //Creating new instance in the Main class
 public class ChainStore
 {
     public static void Main()
     {
         var purchaseDetails = new PurchaseDetails();
     }
 }

 //how i call it in the constructor (using the RandomNumber method from above)

 public class PurchaseDetails
 {
     public PurchaseDetails()
     {
         this.CardID = RandomNumber(1000, 9999);
     }
 }

So now, for example if i want to create

var purchaseDetails2 = new PurchaseDetails();

and rerun the program(with F5/ctrl+F5) I want use the same random generated value from the first time i run the program. In other words I want the Card.ID to have the same value not a new random generated one;

Do I have to save all the values in a List or Array? And if yes how do I do that? Thanks in advance!


Solution

  • I want use the same random generated value from the first time i run the program.

    The overload of Random() you are using internally generates a seed for the pseudo-random number generation algorithm.

    To get the same result every run, supply a seed of your choosing with the alternate constructor

    private static readonly Random random = new Random(42);
    

    As long as your program otherwise runs in a deterministic order, you will get the same "random" numbers (it won't be deterministic if for example it uses multiple threads or changes flow based on user input).