[SOLVED] C# duplicate random numbers | SoloLearn: Learn to code for FREE!


[SOLVED] C# duplicate random numbers

While testing in a C# code, I found that the same numbers were being generated by my random() method. Is there any way around this? Here is a code which shows it happening: https://code.sololearn.com/cgK81DST69JK/?ref=app

1/26/2019 7:18:06 AM


2 Answers

New Answer


Declare and initialize the Random object outside the scope of the method, and use the same object for generating random numbers instead of dynamically creating a new one every time the function is called. static Random rand = new Random(); static void random() { int a = rand.Next(0, 6); int b = rand.Next(0, 6); Console.WriteLine($"{a} | {b}"); }


Thank you Hatsy Rei!