Hi I'm trying to generate two random numbers using the ramdom class. However, I always get the same random number for both variables. Is there a way I can get two distinct numbers? Thanks.

Recommended Answers

All 2 Replies

You need to use the .Next() method.

Random rdm = new Random();
                        Console.WriteLine( rdm.Next( 0 , 100 ) );
                        Console.WriteLine( rdm.Next( 0 , 100 ) );

If you are creating two instances of the random class at the same time you will get the same numbers. The random class generates numbers based on a seed value. The seed value is based on the current system clock time so if you create two objects at the same time they will have the same seed and will generate the same sequence of numbers.

If you create a single instance and take each number in turn from the same sequence (as pierlucSS showed you above) then you wont get repeats (or if you do its because the numbers are random, not because they are duplicates).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.