Home > other >  How can I fill the array of structure randomly?
How can I fill the array of structure randomly?

Time:02-23

My problem is, that the ALL values are changing after iteration.

I wanna that every value in the array till last index, will be different. If use debagger I can see that the code generates everything correct, but I really can not understand why it copies the last result to all objects.

public void RandomFillArray(Teacher[] arr, int lastIndex)
{
    var rnd = new Random();
    var temp = new Teacher();
    var posns = new[] {"state", "private"};

    for (var i = 0; i < lastIndex; i  )
    {
        temp._ratePoints = rnd.Next(0, 11);
        temp._expYear = rnd.Next(0, 30);
        temp._position = posns[rnd.Next(0, posns.Length)];
        temp._salary = temp._ratePoints * 1500   temp._expYear * 500;
        arr[i] = temp;
    }

}

If try to print the array it looks like:

Rating: 10;    Experience: 6;    Position: private;  Salary: 18000.

Rating: 10;    Experience: 6;    Position: private;  Salary: 18000.

Rating: 10;    Experience: 6;    Position: private;  Salary: 18000.

...

Thank you very much in advance

CodePudding user response:

Its not "copying" anything, the problem is that your temp variable is a reference to an object and all you're doing us updating the values of that reference.

The easiest solution is just to move var temp = new Teacher(); into your loop.

CodePudding user response:

This line is responsible: arr[i] = temp

You assign a single instance of teacher to all teachers in the array, so they are the same instance. If you change properties of that instance, you will apply these changes then to all teachers in the array(because they are same).

You need to move the initialization of the instance to the loop body:

for (var i = 0; i < lastIndex; i  )
{
    var temp = new Teacher();
    temp._ratePoints = rnd.Next(0, 11);
    temp._expYear = rnd.Next(0, 30);
    temp._position = posns[rnd.Next(0, posns.Length)];
    temp._salary = temp._ratePoints * 1500   temp._expYear * 500;
    arr[i] = temp;
}
  •  Tags:  
  • c#
  • Related