-1

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());

}
Stephen Reindl
  • 5,659
  • 2
  • 34
  • 38
Aine_Rock
  • 1
  • 1

1 Answers1

2

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());

    }
mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • Still doesn't show the actual values just the type it is eg hseEmployee – Aine_Rock Nov 10 '16 at 22:37
  • @Aine_Rock this is because you return the item of collection which hseEmployee, you need to cast it to proper object and write emp[index].PropertyName. Don't use ArrayList better use List. Does this 2 classes share same interfaces ? – mybirthname Nov 10 '16 at 22:39
  • @Aine_Rock what are the properties of this classes ? You want to show some property or what ? What do you expect to see if you call Doctor.ToString() ? – mybirthname Nov 10 '16 at 22:41
  • I am looking to show for example Aine Porter 5 20000 – Aine_Rock Nov 10 '16 at 22:43
  • So What are the name of the properties ?! how do you expect magically to be shown when you call ToString() ? – mybirthname Nov 10 '16 at 22:45