I am making an ArrayList of Bar Object. I then want to be able to modify the BarType member contained in the ArrayList. I created a shortened version of my code that actually is doing what I want it to do, but I do not understand why it is doing it.
In the code I create two Bar objects and stuff them into a ArrayList. I pull the last Bar Object out of the list cast it to Bar. But TMP is a new instance of the BAR object, yet when I change the value in TMP it changes the values in my arraylist. I am not sure why it does it or if this is the best way to change the BarType value in an ArrayList.
Below is the code:
ArrayList barArray = new ArrayList();
Bar myBar = new Bar(10,20);
barArray.Add(myBar); // I want to create and keep adding Bar object to my arraylist
myBar = new Bar(30, 40);
barArray.Add(myBar);
Bar tmp = new Bar(5,6);
tmp = (Bar)barArray[myBar]; // extracting the last Bar Object
tmp.BarType = true;
tmp.High = 100; // too my surprise this change the value in the ArrayList
So below is my Bar class:
public class Bar
{
public double High, Low;
public bool BarType; // I want to be able to modify this variable
public Bar(double Low, double High)
{
this.Low = Low; this.High = High;
}
}
ArrayListinstead ofList<Bar>?