1

I am using the following code:

var a = (new Random()).Next(2);

This is inside of a small loop. Each time it sets the value of a to zero. Can someone give me some advice on what I am doing wrong?

Update

Thanks for the advice given but I still see just the one number:-( Here is my code after I added the suggestions:

        var r1 = new Random();
        var r2 = new Random();

        foreach (var entry in this.ChangeTracker.Entries()
                     .Where(
                          e => e.Entity is IAuditableTable &&
                         (e.State == EntityState.Added) ||
                         (e.State == EntityState.Modified)))
        {
            IAuditableTable e = (IAuditableTable)entry.Entity;
            if (entry.State == EntityState.Added)
            {
                e.CreatedBy = r1.Next(2);
                e.CreatedDate = DateTime.Today.AddDays(-1 * r2.Next(30));
            }
            e.ModifiedBy = r1.Next(2);
            e.ModifiedDate = DateTime.Today.AddDays(-1 * r2.Next(30));
        }

Always the CreatedBy and ModifiedBy get a 0 :-(

2 Answers2

5

Move random creation out of the loop:

var random = new Random();

foreach(var item in items)
{ 
   var a = random.Next(2);
   // ...
}

Because new random instance is initialized with Environment.TickCount, i.e. milliseconds from last machine start, thus if you are creating them too fast, random instances will have same seed (which means instances will return exactly same 'random' values):

public Random() : this(Environment.TickCount)
{
}

too fast means within 16 milliseconds, between updates of Environment.TickCount value.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Thanks. I did this but I still notice the same (always zero) value. I updated the question with the actual code. Do you have any ideas. I don't know what else to try. –  Jul 06 '13 at 07:00
  • @Melina `Next(2)` means only two possible values `0` and `1`. Your code should work now - try to run it several times. – Sergey Berezovskiy Jul 06 '13 at 07:11
0

The correct way is:

var random = new Random();
while (true)
{
  var a = random.Next(2);
  // use a
}
tech-man
  • 3,166
  • 2
  • 17
  • 18