How do I have two random values ​​per line give different values?

For example, if I have a class:

public class Class
{
public Random r;

public Class()
{r= new Random()}
}

and then create two instances:

Class a = new Class();
Class b = new Class();

and call r sequentially, r for both will give the same value. I read that this is because the default constructor for Random uses time to provide "randomness", so I was wondering how I can prevent this. Thanks in advance!

+5
source share
4 answers

One way to achieve this is to do it r static.

staticmeans that only one will exist Random rand it will be used for all instances of the class.

The code will look like this:

public class Class() { static Random r = new Random(); }

Class a = new Class();
Class b = new Class();

, [ThreadStatic] ( Random)

, [ThreadStatic] - , , .

+5

. , - , .

, Random - .

+4

One possibility in this case is to make Random a static so that it is created only once.

public class Class{
  private static Random r = new Random();        
  //the rest of your class
}

The problem is that you create two classes almost simultaneously, so they will use the same seed (since it is based on the current time, by the way) and will produce the same sequence of numbers.

+2
source

Try the following:

public class TestClass
{
    private static int seed = Environment.TickCount;


    public TestClass()
    {
        DoStuff();
        DoStuff();
        DoStuff();
        DoStuff();
    }

    private void DoStuff()
    {
        var random = new Random(seed++);
        int index = random.Next(30) + 1;

        //Console.Write(index);
    }
}
+1
source

All Articles