-1

Consider the following:

SomeObject o1 = new SomeObject("obj 1");
SomeObject o2 = new SomeObject("obj 2");

for (int i = 0; i < 10; i++)
{
     o1.Method();
     o2.Method();
}

Where:

public class SomeObject
{
    string name;
    public SomeObject(string name)
    {
        this.name = name;
    }
    public void Method()
    {
        Console.WriteLine($"{name}:  {new Random().Next(1, 101)}");
    }
}

Output:

obj 1: 99

obj 2: 99

obj 1: 99

obj 2: 99

obj 1: 99

obj 2: 99

obj 1: 99

obj 2: 99

obj 1: 99

obj 2: 99

That's doesn't looks like random numbers

Community
  • 1
  • 1
Devy
  • 3
  • 1

2 Answers2

1

You need to create the Random once, and then use it many times.

Like this:

SomeObject o1 = new SomeObject("obj 1");
SomeObject o2 = new SomeObject("obj 2");
var random = new Random();

for (int i = 0; i < 10; i++)
{
    o1.Method(random);
    o2.Method(random);
}    

With this class:

public class SomeObject
{
    string name;
    public SomeObject(string name)
    {
        this.name = name;
    }

    public void Method(Random random)
    {
        Console.WriteLine($"{name}:  {random.Next(1, 101)}");
    }
}

Or you could pass the Random instance in the constructor or something. The important thing is: the numbers are only "random" within the same instance.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
0

If the same seed is used for separate Random objects, they will generate the same series of random numbers.

Seed is the starting value.

Docs

Shad
  • 1,185
  • 1
  • 12
  • 27