Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# random function returning the same value [duplicate]

Tags:

c#

random

Possible Duplicate:
Random number generator not working the way I had planned (C#)

I have made a simple routine which generates a random number

private int randomNumber()
{
    Random random = new Random();
    int randomNum = random.Next(0, 100);
    Response.Write(randomNum);
    return randomNum;
}

I call this at two different stages throughout my page_load in the same way:

// A/B Test
if (randomNumber() <= 50)
{
...

I'm finding though, that both numbers are always the same. Any ideas?

like image 385
Chris Avatar asked Nov 29 '22 02:11

Chris


2 Answers

When you create a Random instance it's seeded with the current time. So if you create several of them at the same time they'll generate the same random number sequence. You need to create a single instance of Random and use that.

like image 160
Dave Carlile Avatar answered Dec 05 '22 03:12

Dave Carlile


new Random() is initialized with current time as a seed. If you call it fast enough, then the seed will be the same and so is the result of Next() call.

like image 30
Ilia G Avatar answered Dec 05 '22 01:12

Ilia G