-2

I have this C# class

 public class EntryClass
    {
        public string Field { get; set; }
        public List<FieldKeyValuePair<string, string>> FieldKeyValPairs { get; set; }

        public bool Equals(EntryClass other)
        {
            return Field.Equals(other.Field)
                && FieldKeyValPairs.Equals(other.FieldKeyValPairs);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((EntryClass)obj);

        }
    }

    public class FieldKeyValuePair<K, V>
    {
        public K Key { get; set; }
        public V Value { get; set; }

        public bool Equals(FieldKeyValuePair<K, V> other)
        {
            return Key.Equals(other.Key)
                && Value.Equals(other.Value);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((FieldKeyValuePair<K, V>)obj);
        }

    }

trying to do Assert.IsTrue(expected.SequenceEqual(actual)); always gives me false, I am seeing that even when expected and actual has same FieldKeyValPairs this expression always hits false && FieldKeyValPairs.Equals(other.FieldKeyValPairs);

EDIT And expected and Actual is of type

 List<EntryClass> expected = new List<EntryClass>(); // TODO: 
         List<EntryClass> actual = new List<EntryClass>();
Justin Homes
  • 3,739
  • 9
  • 49
  • 78
  • He is explaining well enough, but its a formatting problem. His problem is described at the end of the code sample he provided. – Lynch May 05 '13 at 22:27

2 Answers2

2

May be you just forgot to override GetHashCode(). Some comparison algorithm compares the hash code first to speed up the computation.

See this answer for more info: Why is it important to override GetHashCode when Equals method is overridden?

Community
  • 1
  • 1
Lynch
  • 9,174
  • 2
  • 23
  • 34
  • I did forget that i added them but still i am noticing that when return Field.Equals(other.Field) && FieldKeyValPairs.Equals(other.FieldKeyValPairs); executes it is not hitting the equals override for this class FieldKeyValPairs – Justin Homes May 05 '13 at 22:32
  • @Justin You should add more unit tests to test every methods independently. May be you could start with testing the FieldKeyValuePair.Equals function directly instead of testing them through a list comparison. – Lynch May 05 '13 at 22:42
0

I had to change return Field.Equals(other.Field) && FieldKeyValPairs.Equals(other.FieldKeyValPairs);

TO

      return Field.Equals(other.Field)
            && FieldKeyValPairs.SequenceEqual(other.FieldKeyValPairs);
Justin Homes
  • 3,739
  • 9
  • 49
  • 78