3

I have a silly question here. I define a class with many data members, like this:

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'm writing unit test code and want to compare two instances of class A. But I found this doesn't work:

Assert.AreEquals(a1, a2);

I must override Equals method to do that? C# can't help with this by default? Or I can serialize these two guys and compare the filestream?

Thank you.

bychance
  • 282
  • 4
  • 14
  • 4
    It depends on what kind of comparison you want. The default Equals just compare the two instances and not its contents. Override and compare each and every item. – Zenwalker Mar 28 '12 at 06:25
  • @zenwalker you'd better post your comment as an answer – Arseny Mar 28 '12 at 06:27
  • @Arseny Its not really an answer the OP is looking for i guess. Plus do not like getting downvoted too :D – Zenwalker Mar 28 '12 at 06:28
  • You may use reflection to compare value type properties, but for reference type properties this does not work. Also possible duplicate of http://stackoverflow.com/questions/506096/comparing-object-properties-in-c-sharp – daryal Mar 28 '12 at 06:53

1 Answers1

6

The default equality implementation, for reference types, is reference equality: "is this the same instance". For equivalence, yes, you should write that yourself if you need that, but: it is rarely all that useful really (and there's a problem, because if you override Equals you should override GetHashCode too, with a suitably parallel implementation.

Personally, I'd compare manually in your unit test if this code isn't part of your main system.

Lists are a pain too, since there are three options:

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

You probably mean the last, but that is the same problem, repeated.

Re serialization: that is tricky too, since it depends on the serializer and the contents. I wouldn't recommend that route unless a: your type is already being used for serialization, and b: your chosen serializer guarantees the semantic you mean. For example, BinaryFormatter does not (I can provide a concrete example if you want, but trust me: this is not guaranteed).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • It is just a thought in my mind: serializer can deal with my custom class recursively, so there must be a "comparer" to do it in the same way. OK. I'm interested in your example about BinaryFormatter. Thank you. – bychance Mar 28 '12 at 06:43