Generated random numbers are always equal

c#, random

Solution

Create your random object static

public class MyClass
{
   public static Random rand = new Random();

   public int MyMethod()
   {
       return rand.Next() % 10 + 1;
   }
}

Random works on `System.DatTime.Now.Ticks`.

If we do like this

Random rand = new Random();

internally it happens as

Random rand = new Random(System.DateTime.Now.Ticks);

Just think for a moment the only thing which is not constant in system is System Time.

When ever using Random class make its object once and use its method `Next()` where ever you want. You will find this situation in loops when random object is created inside loops.

In your code they are created one after another, they get created by same Ticks seed value.

Create your random object static and then they won't be same.

Problem

I have a class: ``` public class MyClass { public int MyMethod() { Random rand = new Random(); return rand.Next() % 10 + 1; } } ``` And 2 objects of it: ``` MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(); ``` The problem is that `obj1.MyMethod() == obj2.MyMethod()` always. Why does it happen? What's the best way to avoid it?

Original source

Related problems