Search code examples
c#wpfrandomstatic-variables

Why the behaviour of a Random variable differs when defining as static or not-static?


my question is: why the behaviour the variable "_random" changes when it is defined as static / non-static?

==> when static defined: _random.nextDouble() returns really random values.

==> when not: _random.nextDouble() returns almost the same values.

class Shape   
{  
    protected Canvas _canvas;
    protected UIElement _element;
    static Random _random = new Random();

    public Shape(Canvas canvas)
    {
        _canvas = canvas;
    }

    public void Draw()
    {
        double val1 = _canvas.ActualWidth * _random.NextDouble();
        double val2 = _canvas.ActualHeight * _random.NextDouble();
        _element.SetValue(Canvas.LeftProperty, val1);
        _element.SetValue(Canvas.TopProperty, val2);
        _canvas.Children.Add(_element);
    }

}


public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Shape s1 = new Circle(MemoCanvas);

        for (int i = 0; i < 100; i++)
        {
            Shape shape1 = new Circle(MemoCanvas);
            shape1.Draw();

            Shape shape2 = new Square(MemoCanvas);
            shape2.Draw();

        }
    }
}

Note: somehow I couldnt format my post, sorry.

Best Regards


Solution

  • Because you are creating a new Random object for each Shape object that you create in the loop, which means that they will produce the same series of random numbers as the random generator is seeded from the system clock.

    This always happens if you create new Random instances too close in time.

    When you define the _random field as static, only one single Random object will be created and used across all instances of the Shape class.