Q: Random String Generator Returning Same String

D: I've developed a random string generator but it's not behaving quite as I'm hoping. My goal is to be able to run this twice and generate two distinct four character random strings. However, it just generates one four character random string twice.

Test Case #2


File ID: #1122519-0-cc


public class RandomStringGenerator
{
    private static readonly Random Random = new Random();
    public static string RandomString(int size)
    {
        var builder = new StringBuilder();
        for (int i = 0; i < size; i + +)
        {
            char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * Random.NextDouble() + 65)));
            builder.Append(ch);
        }
        return builder.ToString();
    }
}

  1. Note that instance members of the `Random` class are NOT documented as being thread-safe, so if this method is called from multiple threads at the same time (highly likely if you are making a web app, for example) then the behaviour of this code will be undefined. You either need to use a lock on the random or make it per-thread.
  2. Also, you can get a random uppercase letter by using `ch = (char)random.Next('A','Z');` a lot simpler than the unreadable line `ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));` from the original post. Then if you want to switch it to lowercase, you can easily switch to `(char)random.Next('a','z');`
  3. Remember [the upper bound is exclusive](http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx), so `ch = (char)random.Next('A','Z');` would never return `'Z'`. So you'd need `ch = (char)random.Next('A', 'Z' + 1);` to include the `'Z'`.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: