dimanche 7 juillet 2019

C# Recursively check the object properties and compare two objects property by property

I have recently written a simple method on a class that does a DeepCopy of all properties and returns the new property. Below are three sample classes and the DeepCopy method:

class Person
{
    public int Age {get; set;}
    public string Name {get; set;}
    Public Address address {get; set;}
    public List<Person> Children {get; set;}
}

class Address
{
    public string StreetAddress {get; set;}
    public int ZipCode {get; set; }
    public Region region {get; set;}    
}

class Region
{
    public string City {get; set;}
    public string Country {get; set;}
}

public static Person DeepCopy(this Person p)
{
    return new Person
    {
        Age = p.Age,
        Name = p.Name,
        Address = p.Address,
        Children = p.Children
    }
}

I want to write unit tests, to test:

  1. All the properties of the source object are copied to the second object and the values are identical.
  2. Using reflection, get the list of the properties recursively (since each object can have a property which is another type which itself has a property...) and make sure the DeepCopy method copies all the properties. The reason for this test is to fail, if a new property is added to the Person class and not copied to the new object in DeepCopy method.

I have already tried using reflection to get all the properties, but one of the problems I have is at some point, it gets stuck in a loop.





Aucun commentaire:

Enregistrer un commentaire