bychance
bychance

Reputation: 282

How to compare two instances' contents in C#?

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.

Upvotes: 3

Views: 598

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062550

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).

Upvotes: 6

Related Questions