I have two objects with the same type and values how can I compare them by value?
exp:
class Person
{
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public Address Address { get; set; }
}
class Address
{
public string City { get; set; }
public int ZipCode { get; set; }
}
var p1 = new Person()
{
Name = "John doe",
BirthDate = new DateTime(2000, 1, 1),
Address = new Address(){
City = "some city",
ZipCode = 123456
}
};
var p2 = new Person()
{
Name = "John doe",
BirthDate = new DateTime(2000, 1, 1),
Address = new Address(){
City = "some city",
ZipCode = 123456
}
};
so how can I compare these objects with value?
Mabey in future I wanna change my objects so I need a general way that not depends on object properties names and types
Convert each object into a json string, with all properties/fields sorted by name, then compare two strings. this is slow, but it works.
Using reflection methods, compare each property/field one by one. Actually the json library do the same job. Doing the comparison yourself will save the time converting to string, but you have to dive into the nested types.
If the datatype is just POCO type, maybe protobuf is a good choice. It introduces a lot advantages: