2

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?

Leri
  • 12,367
  • 7
  • 43
  • 60

2 Answers2

11

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.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

you are creating a new Random every time. When you create a new instance of Random without explicitly specifying the seed value it uses System.DatTime.Now.Ticks as the seed. Due to the speed of calls they are happening at the same 'Tick' so the same seed value is used. As all Random instances generate the exact same sequence of 'random' number for the same seed value the same 'random' value is generated by both instances.

This has been covered many times before on the site and you should search for one of those answers.

But basically you need to create your Random object once and reuse it. This could be done statically , or at least as a class variable.

You should read this question and its answers to find a better approach.

Community
  • 1
  • 1
Sam Holder
  • 32,535
  • 13
  • 101
  • 181