0

Say I have a class something like this:

public class MyClass
{
    public int[] BunchOfNumbers { get; set; }
    
    public int SomeOtherNumber { get; set; }
}

I'd like to write an equality method that has the following prototype:

public bool AreItemsEqual(IReadOnlyList<MyClass> objA, IReadOnlyList<MyClass> objB)
{
    ...
}

If and only if objA is logically equal to objB, then it returns true but otherwise return false. There's a lot of complexity here as it's sort of like a 2D array but also have to think about things that could be null.

Any easy implementation for this?

millie
  • 2,642
  • 10
  • 39
  • 58
  • 1
    Layer it. Give each class it's own equality method. That's the normal way of working. For comparing collections: see the dupe – JHBonarius Aug 05 '22 at 19:23
  • https://learn.microsoft.com/en-us/dotnet/api/system.collections.structuralcomparisons.structuralequalitycomparer?view=net-6.0 – Poul Bak Aug 05 '22 at 19:30
  • 1
    One thing to keep in mind when designing any implementation of deep comparisons is circular references and how you will deal with them. If an object lower in the graph refers to an object higher in the graph (or elsewhere), you'll encounter an infinite recursion scenario. – Mike Hofer Aug 05 '22 at 20:52
  • @JHBonarius I do not have control over `MyClass` so I cannot give it an equality method. And all the other types are primitive or an array of primitives, so I can't give them equality methods. – millie Aug 08 '22 at 13:40
  • That are kind or details that are important to put in your question body. Else your question will be closed as dupe. Also the `My` in `MyClass` kind of hints that you have control over that class... so next time try to be complete and clear in your question. – JHBonarius Aug 08 '22 at 14:37

1 Answers1

0

Override method equals inside object class you want to compare its instance, then you’ll have to implement method equals to compare the attribute of the class

And operation should be done as follow Bool isEqual = Obj1.equals(obj2)

  • But if the object class has non primitive attributes/members, you should override equals method in those non primitive attributes as well – Simon Ragnar Aug 05 '22 at 19:30
  • The problem here is that `MyClass` is not in control for being edited. It only contains the two public properties mentioned (i.e. there's no hidden private state). – millie Aug 08 '22 at 13:38