jeudi 30 mars 2017

Generate Random Number Between 0 and 12 In For Loop (C#)

I'm currently having an issue with randomly generating fake data stored across several arrays. The loop works fine, and all the data is being pulled correctly, however the data is the same for every iteration of the loop which is driving me insane; it doesn't matter if I loop 100 times or 1,000,000 times, it will all be the same.

Random r = new Random(123456);
for (int i = 0; i < 100; i++) {
     temp.Name = names[r.Next(0, 4)];
     temp.Status = status[r.Next(0, 12)];
}

All variables are local to the method, and are created before the loop begins. At the end of each iteration the temp variable is stored within a list of it's type for later access. Everything else works just fine and I'm thinking that maybe it's just the small ranges that are causing the issue. I originally initialized 'r' with an empty constructor to simply use system time as the seed but even that was to no avail.

The random values do change, but only once at page load; for example, if I refresh the page or if I restart the debugging process the values change to a set of different values, however the values are still the same throughout the 100 'temp' objects in the list; should I be re-initializing the 'temp' variable with each iteration of the loop as well?




Aucun commentaire:

Enregistrer un commentaire