2

I have such code: String text has some {AVATAR}in it

    if (text.Contains("{AVATAR}"))
        text = Regex.Replace(text, "{AVATAR}", m => rand_avatars());
public string rand_avatars()
{
    string[] text = avatars.ToArray();
    Random rand = new Random(DateTime.Now.Millisecond);
    return text[rand.Next(text.Length)];
}

But after replace in out I receive 2 same strings from avatars. Why?

obdgy
  • 449
  • 2
  • 8
  • 11
  • I had similar problem: http://stackoverflow.com/questions/15162048/very-weird-code-with-random-works-different-when-i-use-breakpoint – Kamil May 22 '13 at 13:28

2 Answers2

10

This is probably because DateTime.Now.Millisecond has not changed between the calls, and therefore the same seed is being used twice for the random number generator.

You should make the Random object a field and initialise it once only, then re-use it in rand_avatars().

Alternatively, initialise it once as a local before doing the replace, and pass it in to rand_avatars(Random random) (having added Random as a parameter to rand_avatars()).

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
5

Use the same Random object and just call Next every time. If you create a new Random object for every number, you'll get similar results.

private Random _r = new Random();

void Foo()
{
    /// ...

    if (text.Contains("{AVATAR}"))
        text = Regex.Replace(text, "{AVATAR}", m => rand_avatars());

    /// ...
}

string rand_avatars()
{
    string[] text = avatars.ToArray();
    return text[_r.Next(text.Length)];
}

Edit: By the way, the if clause is unnecessary because Regex.Replace won't replace anything if the pattern isn't matched.

fero
  • 6,050
  • 1
  • 33
  • 56