0

For some TreeView I want to test lots of values for the Background Property of the items.

So I have a tree that is filled with 200 items right now.

These are the possible values:

public enum EnumItemState
{ 
    Default,
    Red,
    Green,
    Yellow,
}

Now I wanted to quickly test different values in the view, so I wrote this code:

    private EnumItemState GetRandomItemState()
    {

        var rand = new Random();

        var val = rand.Next(0, 3);

        switch (val)
        {
            case 0:
                {
                    return EnumItemState.Red;
                }
            case 1:
                {
                    return EnumItemState.Green;
                }
            case 2:
                {
                    return EnumItemState.Yellow;
                }
            default:
                {
                    return EnumItemState.Default;
                }
        }
    }

But it is not random at all. All of the values are the same for one run.

Having breakpoints somewhere in my "Random" method, I get different, "more random" results.

What is happening here?

How to get better random results?

Is it some optimization, so all my Randoms are created with the same time seed and therefore get the same result?

Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113

2 Answers2

1

You're creating a new Random object every time you call your method which is being seeded with the same value (it's based on the current time) so you keep getting the same random value.

Do this instead:

void CallingMethod()
{
    Random rnd = new Random();

    for (int i = 0;i < 200;++i)
        EnumItemState state = GetRandomItemState(rnd);
}

private EnumItemState GetRandomItemState(Random rnd)
{
    // Same code you had here, but don't create new instance of Random
}
itsme86
  • 19,266
  • 4
  • 41
  • 57
0

I'm going to assume you're calling this very frequently in a tight loop (i.e., little to no time between calls)

The default ctor for Random looks like this:

public Random() : this(Environment.TickCount)
{
}

See that Environment.TickCount? If you try new'ing multiple Random instances very quickly (i.e., before that tick count changes), you will effectively get the exact same sequence of random numbers - hence "PseudoRandom".

You can do one of a couple things:

  • Wait a while between calls
  • Manually pass in a seed to the ctor
  • Use the prngs in the System.Security namespace
JerKimball
  • 16,584
  • 3
  • 43
  • 55