0
I am trying to create an object called "State", however I would like the DDD of each object, when creating, to be generated randomly.
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 as we spin:
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 came out repeated:
State: Pernambuco
DDD: 60
State: Pará
DDD: 60
State: Piauí
DDD: 60
State: Paraná
DDD: 60
How can I do for each object, when creating the constructor, have its own randomly generated DDD?
Tip: http://www.macoratti.net/12/05/c_rand1.htm
– Maury Developer
The reason is that it creates only one object by execution. Unless you repeat dry per line.To facilitate understanding, your result (ramdom) is being executed only once. If it were inside a for() or calling the object each state would run unlimited times. Therefore Voce has only one generated number. Time as the colleague said does not influence anything. To do the test, in place of toString put Random() is more or less like this.Writeline(pa.Random())
– Risk