Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contains() returns false even though it should return true

Tags:

c#

I am currently trying to check if some list of mine contains an object. The list is a list of of an object which is made up of a struct which contain 2 fields.

I am trying to run this small code:

if(m_EatingMoves.Contains(i_Move))
{
  ....
}

But the expression will return false even though I can surely see on debug that the Move i want is inside the *m_EatingMove* list, I thought that the problem might be that I don't have an override for Equals in my struct so I found an implementation here on StackOverFlow, but the expression still returns false. Any Idea besides implementing my own Contains() ?

This is the struct:

    public struct Cell
    {
        public int Row;
        public int Col;

        public Cell(int i_Row, int i_Col)
        {
            this.Row = i_Row;
            this.Col = i_Col;
        }

        public override bool Equals(object obj)
        {
            if (!(obj is Cell))
                return false;

            Cell cell = (Cell)obj;
            return cell.Col == Col && cell.Row == Row;
        }
    }

Now I have another object which is made up of the above struct:

    public class Move
    {
        private Board.Cell m_Source;
        private Board.Cell m_Destination;

        public Move(Board.Cell i_Source, Board.Cell i_Destination)
        {
            m_Source = i_Source;
            m_Destination = i_Destination;
        }
....(Properties, etc..)

Finally we have the list which is initialized by the constructor

private List<Move> m_EatingMoves
like image 891
Steinfeld Avatar asked Oct 15 '25 03:10

Steinfeld


1 Answers

You also need to override the GetHashCode method so that two cells that are equal return the same hash code. A pattern often used is to xor the hash codes of items being compared, e.g.:

public struct Cell
{
   [...]
   public override int GetHashCode()
   {
       return Row.GetHashCode() ^ Col.GetHashCode();
   }
}

Without overriding this method, data structures may not correctly compare for equality, causing the behavior you observed. The MSDN GetHashCode has additional documentation on how this method is used within the framework.

like image 152
drf Avatar answered Oct 17 '25 17:10

drf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!