How to Display a Random Object in C# [Duplicate]
I'm Just Learning C# and Cannot Display a Random Object in an Arraylist. Code as Follows ` Arraylist Emp = New Arraylist(); hseEmployee E3 = New...
I'm just learning C# and cannot display a random object in an arraylist. Code as follows `
ArrayList emp = new ArrayList();
hseEmployee e3 = new hseEmployee("Aine","Porter",5,26000);
hseEmployee e4 = new hseEmployee("Tara", "Standard", 2, 20000);
hseEmployee e5 = new hseEmployee("John", "Porter", 7, 28000);
hseEmployee e6 = new hseEmployee("Keith", "Porter", 3, 22000);
hseEmployee e7 = new hseEmployee("Aine", "Porter", 5, 26000);
emp.Add(e3);
emp.Add(e4);
emp.Add(e5);
emp.Add(e6);
emp.Add(e7);
Doctor d = new Doctor("Niamh","Doctor",5,40000);
Doctor d1 = new Doctor("Briege", "Doctor", 13, 100000);
Doctor d2 = new Doctor("Thomas", "Doctor", 9, 60000);
Doctor d3 = new Doctor("Ciara", "Doctor", 1, 30000);
Doctor d4 = new Doctor("Chris", "Doctor", 6, 50000);
emp.Add(d);
emp.Add(d1);
emp.Add(d2);
emp.Add(d3);
emp.Add(d4);
for (int i = 0; i <=10; i++)
{
Random r = new Random();
int index = r.Next(emp.Count);
richTextBox1.AppendText(emp[index].ToString());
}
Put Random outside the for loop.
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random
When you have Random in the loop you are calling the constructor of Random with the same seed value and because of that you have same number, not random.
Random r = new Random();
for (int i = 0; i <=10; i++)
{
int index = r.Next(emp.Count);
richTextBox1.AppendText(emp[index].ToString());
}