I have been trying to check my arraylist to see if an object already exsists, but it always returns false. Does any one have a sugestion to what I am doing wrong with the arrayList.
ArrayList arr;
void Init()
{
arr = new ArrayList();
}
void Fred()
{
CauseAssignment ca = new CauseAssignment(Param1.Text, Param2.Text);
if(!arr.Contains(ca))
arr.Add(ca);
}
public class CauseAssignment
{
private string _Path;
public string Path
{
get { return _Path; }
}
private string _DelimRootCause;
public string DelimRootCause
{
get { return _DelimRootCause; }
}
public CauseAssignment(string path, string delimRootCause)
{
_Path = path;
_DelimRootCause = delimRootCause;
}
public override string ToString()
{
return _Path;
}
}
The
Contains()methods of ArrayList determine equalitys using the implementation ofEquals()available on the objects you store.If you want two different instances of your class to be considered equivalent, you would need to override the
Equals()method to return true when they are. You should also, then, overloadGetHashCode()for consistency and usability in dictionaries. Here’s an example: