Nick
Nick

Reputation: 5892

Why is a duplicate random string generated by C# method

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();
        }

Upvotes: 2

Views: 719

Answers (4)

Bob Moore
Bob Moore

Reputation: 6894

Executed twice in a row how fast ? the seed of Random is time-dependent, so if you're testing programmaticaly, this could happen. I'd create the Random object elsewhere once, then refer to it in the method.

Upvotes: 1

Tim S.
Tim S.

Reputation: 56556

Move your Random object outside the method so that the same one will be used on repeated calls.

static Random random = new Random();

The problem with what you've got now is that the Random class uses the current time as its seed value, so if it is created twice in rapid succession, both will have the same seed, and so produce the same random string.

Upvotes: 1

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20775

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.

Upvotes: 2

Oded
Oded

Reputation: 499212

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;
    }
}

Upvotes: 8

Related Questions