kirchu

Hello everybody.
Here is the code
ArrayList ar = new ArrayList();
ar.Add(new TileInfo("picture1",10));
ar.Add(new TileInfo("picture1", 20));
ar.Add(new TileInfo("picture1", 30));
ar.Add(new TileInfo("picture1", 40));

foreach (TileInfo o in ar)
{
listBox1.Items.Add(o.Path + " " + o.AvgColor);
}
listBox1.Items.Add(ar.Count);

TileInfo k = new TileInfo("picture1", 10);
ar.Remove(ar.IndexOf(k));

foreach (TileInfo o in ar)
{
listBox1.Items.Add(o.Path + " " + o.AvgColor);
}

listBox1.Items.Add(ar.Count);

My question is:
Why do I still get the same output even though I remove an object from the arraylist
Maybe the way I remove it is wrong...
Any ideas!

kiril



Re: Visual C# General Q: Remove an instance of a class from an ArrayList

frederikm

Hi

http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.remove.aspx

This method determines equality by calling Object.Equals.

The problem with your code above is that you tileinfo.equals on the object you want to remove

so, you need to override the Equals method to return true if the values you used for the constructor are the same..

Hope this helps you out, please close the thread if it does







Re: Visual C# General Q: Remove an instance of a class from an ArrayList

kirchu

I have searched through the web for a suitable solution, but I could not find it. Could you please provide me with a sample code how to solve this problem. I am sorry for bothering you, but I really do not get this overriding and stuff.

Thanks in advance,

kiril






Re: Visual C# General Q: Remove an instance of a class from an ArrayList

frederikm

Hi

try the following:

public class TileInfo {

private String _Name;

private int _Index;

public TileInfo(String name, int index) {

_Name = name;

_Index = index;

}

public int Index {

get { return _Index; }

set { _Index = value; }

}

public String Name {

get { return _Name; }

set { _Name = value; }

}

public override bool Equals(object obj) {

TileInfo other = obj as TileInfo;

if (other == null) { return false; }

if (other._Name == _Name && other._Index == _Index) { return true; }

return base.Equals(obj);

}

}

Hope this helps you out, please close the thread if it does






Re: Visual C# General Q: Remove an instance of a class from an ArrayList

kirchu

Thank you very much for the quick help!