Error while using random

6

I set a random number to fill a dummy table and did so:

    foreach (var usuario in LstUsuarios)
    {
        htmlUsuarios.AppendLine("<tr>");
        htmlUsuarios.AppendLine("<td>" + usuario.Nome + "</td>");
        htmlUsuarios.AppendLine("<td><strong>" + usuario.NomePerfil + "</strong></td>");
        htmlUsuarios.AppendLine("<td>" + usuario.UnidadeGerencial.Txt_Sigla_UG + "</td>");

        for (var i = 1; i <= num_periodos; i++)
        {
            rnd = new Random();
            random = rnd.Next(1, 99);
            htmlUsuarios.AppendLine("<td> " + random + "</td>");
        }
        htmlUsuarios.AppendLine("<td>100</td>");
        htmlUsuarios.AppendLine("</tr>");
    }

However, the same number is always appearing in the application.

The curious thing is that when I debug in visual studio it actually generates different numbers.

What is outside the red line is the part I debugged in VS, I checked with the breakpoints and the numbers were changing. But when I pressed continue in VS it would regenerate the same number as those that are within the red line.

I did not understand why. Any ideas?

    
asked by Joao Paulo 30.05.2014 в 16:18

1 answer

8

Put instância of Random() out of for on your case:

rnd = new Random();
foreach (var usuario in LstUsuarios)
{
    htmlUsuarios.AppendLine("<tr>");
    htmlUsuarios.AppendLine("<td>" + usuario.Nome + "</td>");
    htmlUsuarios.AppendLine("<td><strong>" + usuario.NomePerfil + "</strong></td>");
    htmlUsuarios.AppendLine("<td>" + usuario.UnidadeGerencial.Txt_Sigla_UG + "</td>");

    for (var i = 1; i <= num_periodos; i++)
    {            
        random = rnd.Next(1, 99);
        htmlUsuarios.AppendLine("<td> " + random + "</td>");
    }
    htmlUsuarios.AppendLine("<td>100</td>");
    htmlUsuarios.AppendLine("</tr>");
}

Why?

How the Random is being created within the for each generated item is a new one instance, and so the initial Seed is the same, a fact calculated by Enviroment.TickCount .

About debug:

Precisely because of the Enviroment.TickCount will have another value in debug , and in each F11 for example, it will change the calculation of milliseconds.

    
30.05.2014 / 16:21