-1
public string Weird
{
    get
    {
        int length = 10;
        Random random = new Random();
        string chars = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXZ";
        StringBuilder builder = new StringBuilder(length);

        for (int i = 0; i < length; i++)
        {
            builder.Append(chars[random.Next(chars.Length)]);
        }

        return builder.ToString();
    }
}

Response.Write(Weird);
Response.Write("<br />");
Response.Write(Weird);
Response.Write("<br />");
Response.Write(Weird);

Result : 

9eFZ5XrJxZ
9eFZ5XrJxZ
9eFZ5XrJxZ

I thought the result would be different for each call, but it return same result value. How it could be? Once the variable assigned then the get method will not run again?

saluce
  • 13,035
  • 3
  • 50
  • 67
Expert wanna be
  • 10,218
  • 26
  • 105
  • 158
  • 1
    http://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx <-- required reading if you are going to use Random. – Oded Jul 18 '13 at 20:18
  • Please in future don't use tags in titles. – dav_i Jul 18 '13 at 20:31

3 Answers3

4

From http://msdn.microsoft.com/en-us/library/system.random.aspx:

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.

By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

Community
  • 1
  • 1
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

If you can't make the Random object persist between calls you need to seed it with a pseudorandom value every time you call into that.

Chris Raplee
  • 336
  • 1
  • 5
-2

Dilbert has encountered the same problem back in 2001:

http://dilbert.com/strips/comic/2001-10-25/

Coincidence?

I don't think so.

And random.org agrees : http://www.random.org/analysis/

dbrin
  • 15,525
  • 4
  • 56
  • 83