The following method generates a random string with the given length.
When executed twice in a row, the same string is given. Is anybody able to shed any light on why this might be?
public static string GenerateRandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
You are not using Random correctly.
When calling your GenerateRandomString in a tight loop, it will end up being seeded to the same value many times.
I suggest reading Random numbers from the C# in depth site, by Jon Skeet.
Here is the suggested way to get a Random instance:
using System;
using System.Threading;
public static class RandomProvider
{
private static int seed = Environment.TickCount;
private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>(() =>
new Random(Interlocked.Increment(ref seed))
);
public static Random GetThreadRandom()
{
return randomWrapper.Value;
}
}
Create your random object static
public class MyClass
{
public static Random rand = new Random();
public int MyMethod()
{
return rand.Next() % 10 + 1;
}
}
Random works on System.DatTime.Now.Ticks.
If we do like this
Random rand = new Random();
internally it happens as
Random rand = new Random(System.DateTime.Now.Ticks);
Just think for a moment the only think which is not constant in system is System Time.
When ever using Random class make its object once and use its method Next() where ever you want. You will find this situation in loops when random object is created inside loops.
In your code they are created one after another, they get created by same Ticks seed value.
Create your random object static and then they won't be same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With