Random number in C#
-
IDGenerator.cs --------------
public class IDGenerator { int min, max; public IDGenerator () { this.min = 1000000; this.max = 9999999; } public string GetID () { Random r = new Random(unchecked((int)DateTime.Now.Ticks)); // Produce a number from 00000 through 99999 String myNumber = r.Next(min,max).ToString("00000"); r = null; return myNumber; } }
-
IDGenerator.cs --------------
public class IDGenerator { int min, max; public IDGenerator () { this.min = 1000000; this.max = 9999999; } public string GetID () { Random r = new Random(unchecked((int)DateTime.Now.Ticks)); // Produce a number from 00000 through 99999 String myNumber = r.Next(min,max).ToString("00000"); r = null; return myNumber; } }
Simple. Your creating a new Random number generator with each invocation of
.GetID()
and in creating that generator, your seeding the RNG with the current time, in Ticks. What your doing is telling the new random number generator to start with the seed value and generate a REPRODUCABLE string of numbers. What you should be doing in your IDGenerator class is declaring a class levelRandom
, initializing it once, and using it's.Next
method on each call to.GetID()
.public class IDGenerator
{
int min, max;Random r = new Random(unchecked((int)DateTime.Now.Ticks)); public IDGenerator () { this.min = 1000000; this.max = 9999999; } public string GetID () { // Produce a number from min through max. // Use the RNG created at the class level. String myNumber = r.Next(min,max).ToString("0000000"); return myNumber; }
}
Also, random numbers are not guaranteed to be unique during the life of the generator, so review your policies on what this function will acceptibly return. It's entirely possible that it could return the same number twice (or more) in a row. RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
-
IDGenerator.cs --------------
public class IDGenerator { int min, max; public IDGenerator () { this.min = 1000000; this.max = 9999999; } public string GetID () { Random r = new Random(unchecked((int)DateTime.Now.Ticks)); // Produce a number from 00000 through 99999 String myNumber = r.Next(min,max).ToString("00000"); r = null; return myNumber; } }
The following works for me:
int min = 1000000, max = 9999999; Random r = new Random(); for(int i = 0; i < 5; i++) { Console.WriteLine(r.Next(min, max)); }
- Nick Parker
My Blog | My Articles