1

I have an class like this:

public class Inner {
    public int foo;
    public int bar;
}

and an outer class:

public class Outer {
    public string Name;
    public IEnumerable<Inner> foobars;
}

When I compare two objects, I do this:

// I have to instances of Outer, called A and B
if (A.Equals(B)) {
    // do something
}

I know I need to implement the IEquatable interface or possibly IEqualityComparer (or both), and while this seems simple enough, I have yet to see how to implement it in this situation where Outer has en IEnumerable of Inner objects.

Do I have to implement IEquatable/IEqualityComparer on both Inner and Outer? And how do I make sure the lists are compared properly and not just by reference?

I have searched a lot on stackoverflow and google in general but have missed the proper solution.

galmok
  • 869
  • 10
  • 21
  • Have a squiz at https://blogs.msdn.microsoft.com/jaredpar/2009/01/15/if-you-implement-iequatablet-you-still-must-override-objects-equals-and-gethashcode/ and https://msdn.microsoft.com/en-us/library/bb348567%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 . – mjwills Feb 14 '18 at 12:03
  • Looked at it and I didn't get much wiser. I know about SequenceEqual, but should I use it in the Outer IEquatable Equals method or is it used implicitly? In the Outer Equals method, can I just use `foobars.Equals(other.foobars)` or do I have to specifically use SequenceEqual in the Outer Equals method? – galmok Feb 14 '18 at 12:11
  • `should I use it in the Outer IEquatable Equals method` Yes. To be fair, you could also have just tried it yourself. :) – mjwills Feb 14 '18 at 12:12
  • True. It would probably work, but I wouldn't know if this was the correct way to do it. ;-) – galmok Feb 14 '18 at 12:14
  • 1
    You need to override `Equals` in both `Outer` and `Inner` with your custom logic. This logic will including calling `SequenceEquals` on `foobars`. Don't forget to override `GetHashCode` also to not get surprising results when used in `HashSet`\`Dictionary`. – Evk Feb 14 '18 at 12:25
  • `This logic will including calling SequenceEquals on foobars` The sentence was a bit garbled. You meant that I needed to use SequenceEqual in the Outer Equals method, right? – galmok Feb 14 '18 at 12:53

0 Answers0