Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a duplicate random string generated by C# method

Tags:

c#

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();
        }
like image 750
Nick Avatar asked Mar 18 '26 07:03

Nick


2 Answers

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;
    }
}
like image 86
Oded Avatar answered Mar 20 '26 16:03

Oded


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.

like image 25
Romil Kumar Jain Avatar answered Mar 20 '26 16:03

Romil Kumar Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!