anderici
anderici

Reputation: 77

C#: ArrayList.Clear() clears the wrong array

I'm using ArrayList in C# to do some things. I have 2 ArrayLists (align and best) and, in a specific time, I make best=align inside a "for" routine.

The problem is, in the end of the loop, I do align.Clear, but in this time, the array "best" gets cleared too. After the loop, when I have to use the array "best", I get troubles, because it is cleared and I try to access its index.

What's the problem?

Here is a piece of my code:

public string AntColony()
{
   ArrayList align = new ArrayList();
   ArrayList best = new ArrayList();

   for(int z=0;z<n_ants;z++)
   {
      //do the things i have to do
      //full the array "align" with something (this will have two "adds", so, this array is a 2 lines array)

      score = Score(align);
      UpdatePhero(tao, path, score);

      if (score > score_before)
      {
         score_before = score;
         best = align;
      }
      align.Clear(); //clear the array align
   }
   string s = best[0].ToString() + "\r\n\r\n" + best[1].ToString() + "\r\n\r\n Number of matches: " + n_matches + "\r\n\r\n Score: " + score;

   return s;
}

Thank you!

Upvotes: 0

Views: 136

Answers (2)

SuperOli
SuperOli

Reputation: 1804

Since align is temporary, it can be recreated just before the call to Score and assigned to best when needed:

public string AntColony()
{
    ArrayList best = null;

    for(int z=0;z<n_ants;z++)
    {
      //do the things i have to do
      //full the array "align" with something (this will have two "adds", so, this array is a 2 lines array)

      ArrayList align = new ArrayList();
      score = Score(align);
      UpdatePhero(tao, path, score);

      if (score > score_before)
      {
         score_before = score;
         best = align;
      }
    }

    if (best != null)
    {
        string s = best[0].ToString() + "\r\n\r\n" + best[1].ToString() + "\r\n\r\n Number of matches: " + n_matches + "\r\n\r\n Score: " + score;
        return s;
    }

    // TODO: Report failure here

    return null;
}

Upvotes: 0

rory.ap
rory.ap

Reputation: 35260

Array variables are reference types. When you call best=align you are not copying the contents of align to array, you are making it so that they point to the same place, i.e. they reference the same memory location.

Try best=align.Clone()

Upvotes: 2

Related Questions