user710502
user710502

Reputation: 11471

How to randomize in WPF

Hello I am new to WPF and i do have some experience in ASP.NET but this is totally new like, labels I would be doing label.Content instead of label.Text, anyways.. I am trying to do a simple form, where upon clicking the buton it shows 5 different random numbers..

When I debug this code line by line, it does randomize and has a string of different numbers but when i do not debug and run it at once and click the button it shows the same number for all? , not sure why... so ideally i would have

[1] [23] [45] [24] [34]

It gives me that result if I debug and step through but if I do not debug and just run the program i get

[23] [23] [23] [23] [23]

Any help would be much appreciated

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            int[] numbers = new int[5];
            StringBuilder sb = new StringBuilder();

            List<int> nums = new List<int>();
            foreach (int i in numbers)
            {
               int rand = RandomNumber(1,59);
               nums.Add(rand);
            }


            string numsList = string.Empty;

            foreach (int items in nums)
            {
                numsList += "[" + items.ToString() + "]";
            }

            lblNumber.Content = numsList.ToString();
        }

        private int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }


    }
}

Upvotes: 2

Views: 8342

Answers (1)

brunnerh
brunnerh

Reputation: 184506

You should not create a new Random every time (make it a readonly field instead). The seed may always be the same otherwise when creating new instances shortly one after another. It only works in debug mode since the instances are created more slowly when you step through.

MSDN:

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.

Upvotes: 3

Related Questions