Creating an object with a random internal data [duplicate]
I am trying to create an object called "State", however I would like the DDD of each object, when creating, to be randomly generated.
class Estado
{
public int Resultado { get; set; }
public string Nome { get; set; }
public Estado(string nome)
{
Nome = nome;
rnd();
}
public void rnd()
{
Random random = new Random();
Resultado = random.Next(0, 101);
}
public override string ToString()
{
return "Estado: "+Nome+"\nDDD: "+Resultado;
}
}
But when running:
static void Main(string[] args)
{
Estado pe = new Estado("Pernambuco");
Estado pa = new Estado("Pará");
Estado pi = new Estado("Piauí");
Estado pr = new Estado("Paraná");
Console.WriteLine(pe.ToString());
Console.WriteLine(pa.ToString());
Console.WriteLine(pi.ToString());
Console.WriteLine(pr.ToString());
Console.ReadLine();
}
The result I left repeated:
State: Pernambuco
DDD: 60
Status: Para
DDD: 60
State: Piauí
DDD: 60
State: Paraná
DDD: 60
How can I do to does each object, when creating the constructor, have its own randomly generated DDD?
1 answers
Is why you are instantiating multiple Random
in a super short period of time (less than a millisecond), and it does not allow time for Random
to toggle its seed, and consequently generate a random number other than those previously instantiated.
What you can do is lock a single instance of Random
and not instantiate several, but only one, which will be global for all other uses. Also, lock your Thread so it can't run simultaneously (and avoid generating the same number consecutively)
// dentro da Program, ou qualquer classe estática/não estática
public static Random random = new Random();
class Estado
{
public int Resultado { get; set; }
public string Nome { get; set; }
public Estado(string nome)
{
Nome = nome;
rnd();
}
public void rnd()
{
lock (Program.random) { // evita que o 'random' seja utilizado em threads simultâneos
Resultado = Program.random.Next(0, 101);
}
}
public override string ToString()
{
return "Estado: "+Nome+"\nDDD: "+Resultado;
}
}
The Next()
will always be a pseudo-random number in relation to what was previously generated, this if the seed is the same.
Documentation of Random .
Lock documentation.