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?
Create your random object static
Random works on
System.DatTime.Now.Ticks.If we do like this
internally it happens as
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.