KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Possible Duplicates: c# - getting the same random number repeatedly Random number generator not working the way I had planned (C#) I have a method that builds a queue of ints: public Queue<int> generateTrainingInts(int count = 60) { Queue<int> retval = new Queue<int>(); for (int i = 0; i < count; i++) { retval.Enqueue(JE_Rand.rInt(2001, 100)); } return retval; } JE_Rand.rInt() is just a function that delegates to a function of the Random class: public static int rInt(int exclUB, int incLB = 0) { Random rand = new Random(DateTime.Now.Millisecond); int t = rand.Next(incLB, exclUB); rand = null; return t; } But when I call generateTrainingInts, the same number is enqueued each time. However, if I change rInt to use a static instance of the Random class, instead of a local instance (with function scope as it is defined above), then it appears to work correctly (enqueue random integers). Does anybody know why this happens? Edit: Dear Answerers who didn't read my question thoroughly, Like some of you pointed out, I am looking for a good explanation of why this happens. I am not looking for a solution to the same-number-generated problem, because I already fixed that like I said above. Thanks for your enthusiasm though :) I really just want to understand things like this, because my first implementation made more sense conceptually to me.
Tags (comma-separated)
Save Edits
Cancel