2

I am new to C#, I have a code that calls the same function 3 times that returns a random sting. For some reason my code is returning the same string all the time. Please help.

        public static String randomString()
    {
        String chars = "QWERTYUIOPASDFGHJKLZXCVBNM";
        Random rand = new Random();
        String finalstring = null;

        for (int i = 0; i < 8; i++)
        {
            finalstring += chars[rand.Next(0, chars.Length - 1)];

        }
        return finalstring;

    }

    public void SecondTest()
    {

        Console.WriteLine(Class1.randomString());
        Console.WriteLine(Class1.randomString());
        Console.WriteLine(Class1.randomString());

    }

Sample Output observing: AXCFSDRG AXCFSDRG AXCFSDRG

Anand V
  • 23
  • 7
  • Create random in main class. If you create it closely it uses the same seed therefore the same result. Also try to use google before asking questions. – deathismyfriend Oct 10 '16 at 23:53

3 Answers3

1

You're constructing three separate Random objects, rather than reusing a single Random object (which would be better practice).

Random objects, if you don't provide a seed, are seeded with the current time. In this case, your randomString() method returns so fast that all three Random objects get the same seed, and thus get the same sequence of outputs.

PMV
  • 2,058
  • 1
  • 10
  • 15
1

Based from this SO Answer.

Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

//Function to get random number
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);
    }
}
Community
  • 1
  • 1
jegtugado
  • 5,081
  • 1
  • 12
  • 35
-1

Use RNGCryptoServiceProvider class:

https://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx

Look at RNGCryptoServiceProvider: generate random numbers in the range [0, randomMax)

If you use the extension method in the answer and the following:

    public static String randomString()
    {
        String chars = "QWERTYUIOPASDFGHJKLZXCVBNM";
        Random rand = new Random();
        String finalstring = null;

        for (int i = 0; i < 8; i++)
        {
            finalstring += chars[GenerateRandomNumber(8)];

        }
        return finalstring;

    }

    public static int GenerateRandomNumber(int length)
    {
        using (var randomNumberGenerator = new RNGCryptoServiceProvider())
        {
            return randomNumberGenerator.GetNextInt32(length);
        }
    }

The result will be different each time.

Community
  • 1
  • 1
TheRock
  • 1,513
  • 1
  • 18
  • 19