How can I compare the contents of two instances in C #?

I have a stupid question. I am defining a class with many items, for example:

public class A
    public string Name { get; set; }
    public double Score { get; set; }
    //...many members
    public C Direction { get; set; }
    public List<B> NameValue1 { get; set; }
    public List<string> NameValue2 { get; set; }
    //...many members


Now I am writing a unit test code and want to compare two instances of class A. But I found that this does not work:

Assert.AreEquals(a1, a2);


Should I override a method Equals

for this? C # can't help with this by default? Or can I serialize these two guys and compare the filestream?



source to share

1 answer

The default equality implementation for reference types is reference equality: "this is the same instance". For equivalence, yes, you have to write this yourself if you need it, but: rarely is it really useful (and there is a problem, because if you override Equals

, you must override GetHashCode

too with a suitable parallel implementation.

Personally, I would compare manually in your unit test if this code is not part of your main system.

Lists are also a pain, as there are three options:

  • the same instance of the list
  • different lists with the same content instances
  • different lists with equivalent content instances

You probably mean the latter, but it's the same problem, repeating itself.

Re-serialization: This is also tricky as it depends on the serializer and the content. I would not recommend this route, unless: your type is already being used for serialization, and b: the serializer you choose guarantees the semantics you mean. For example, BinaryFormatter

not (I can provide a specific example if you want, but trust me: this is not guaranteed).



All Articles