Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I have two randoms in a row give different values?

Tags:

c#

For example, if I have a class:

public class Class
{
public Random r;

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

and later create two instances of it:

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

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

like image 734
user794479 Avatar asked Jun 16 '11 05:06

user794479


1 Answers

One way to achieve that would be to make r static.

static means that only one Random r will exist, and it will be shared across all instances of the class.

You code would look like this:

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

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

If you're using threading, you can make it [ThreadStatic] (so that each thread uses its own instance of the Random class)

There's info on how to use [ThreadStatic] here - I haven't used it myself, but it looks quite cool and nifty, and gets rid of any potential threading-related woes.

like image 164
William Lawn Stewart Avatar answered Nov 11 '22 17:11

William Lawn Stewart