Parameter contents changing after class creation

  • Thread starter Thread starter Picqua
  • Start date Start date
P

Picqua

I'm having trouble with a class that accepts an ArrayList as a
parameter. The code looks something like this:

ArrayList arrayOne = new ArrayList();

arrayOne.Add("Hello ");
arrayOne.Add("There!");

someClass sc1 = new someClass(arrayOne);

arrayOne.Clear();
arrayOne.Add("Oh ");
arrayOne.Add("No!");

someClass sc2 = new someClass(arrayOne);

If I step through the code, sc1 is created just fine with the
appropriate contents of arrayOne. However, one I reach the Clear()
call, the contents of the ArrayList inside of sc1 change and "Oh No!"
is then placed inside. In the end I have sc1 and sc2 with identical
ArrayLists. I'm sure there's something obvious I'm missing, any help
would be greatly appreciated.
 
Hello (e-mail address removed),

Just to undestand why this happens your need to understand that arrayList
intance is created in heap, and you send the reference on the single instance
of your arraylist to both classes. So any action to arrayList in each of
these classes will change your arrayList.

To avoid this you need create another new instance of arrayOne and use it
in sc2 class

---
WBR,
Michael Nemtsev [.NET/C# MVP] :: blog: http://spaces.live.com/laflour

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo
 
Just to undestand why this happens your need to understand that arrayList
intance is created in heap, and you send the reference on the single instance
of your arraylist to both classes. So any action to arrayList in each of
these classes will change your arrayList.


Thanks, Michael! Got it figured out now. Thanks again.
 
Back
Top