954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to override the default Contains() method of the arraylist

hello..i've made a structure given below and the objects of that struct are stored in an arraylist

struct node
    {
        public int x;
        public int y;
        public int cost;
        public object parent;
    }

now when i'm adding a new object this type..i want to check if the arraylist already contains the object with the same values..the check should only focus on x,y and cost variables of the object leaving behind the parent variable..how do i achieve this??? which methods of the arraylist should i override?? any help would be appreciated

cool_zephyr
Junior Poster in Training
75 posts since Apr 2009
Reputation Points: 8
Solved Threads: 9
 

you will need to override equals in the struct

struct node
{
    public int x;
    public int y;
    public int cost;
    public object parent;
    public override bool Equals(object obj)
    {
          bool res = false;
          if (obj.GetType()== typeof(node))
          {
              node objCasted = (node)obj;
              res=objCasted.x == x && objCasted.y == y;
          }
          return res;
    }
}

test:

ArrayList ar = new ArrayList();
ar.Add(new node() { x=1, y=2});
if (ar.Contains(new node() { x = 1, y = 2 }))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");
mazzica1
Junior Poster
147 posts since Oct 2011
Reputation Points: 9
Solved Threads: 27
 


the compiler shows a warning about overriding Object.GetHashCode() method tooo..how do i do this??? could you please explain

cool_zephyr
Junior Poster in Training
75 posts since Apr 2009
Reputation Points: 8
Solved Threads: 9
 


i did this and it works

public override int GetHashCode()
        {
            return base.GetHashCode();
        }

thanks a lot for help

cool_zephyr
Junior Poster in Training
75 posts since Apr 2009
Reputation Points: 8
Solved Threads: 9
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: