-4

I type the following code in the VS 2017:

namespace Test {
    class MyClass {
        public static Random randomkey;
        static MyClass() {
            randomkey = new Random();
        }
        public MyClass() {
            randomkey = new Random();
        }
        public int returnkey() => randomkey.Next();
    }
    class Program {
        private static void Main(string[] args) {
            try {
                Console.WriteLine(MyClass.randomkey.Next());
                var x = new MyClass();
                Console.WriteLine(x.returnkey());
                var y = new MyClass();
                Console.WriteLine(y.returnkey());
                Console.ReadLine();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
    }
}

Then click the "Debug" button, I found the results very strange:

Output - The same random number

Then, I tried to click the "Run to Cursor" button and the results became different:

Output - Different random numbers

Why?

ASh
  • 34,632
  • 9
  • 60
  • 82
Dai
  • 7
  • 3

1 Answers1

-1

The random function is using the system time to initialize the random number genertator. So running your code really fast gets the same random number. Add a sleep and then you get expected results.

       private static void Main(string[] args) {
            try {
                Console.WriteLine(MyClass.randomkey.Next());
                System.Threading.Thread.Sleep(5);
                var x = new MyClass();
                Console.WriteLine(x.returnkey());
                System.Threading.Thread.Sleep(5);
                var y = new MyClass();
                Console.WriteLine(y.returnkey());
                Console.ReadLine();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
jdweng
  • 33,250
  • 2
  • 15
  • 20