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

+7

[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

Rowsej

2 Answers

New Answer

+10

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}"); }

+6

Thank you Hatsy Rei!