vendredi 7 juillet 2017

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




Aucun commentaire:

Enregistrer un commentaire