Search code examples
c#.netcompareiequatable

how to compare values of two reference type nested and dynamic objects


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


Solution

  • use json

    Convert each object into a json string, with all properties/fields sorted by name, then compare two strings. this is slow, but it works.

    use reflection

    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.

    use some code generator, e.g. protobuf

    If the datatype is just POCO type, maybe protobuf is a good choice. It introduces a lot advantages:

    • build-in comparison
    • json serialization and deserialization
    • very fast binary serialization and deserialization
    • cross-platform and cross language, integrated well with grpc inter-process communication
    • version compatibility, when new fields added, old data on disk can still be read by app.