4

I came across the following problem: Currently I'm refactoring my project using TDD. There is an existed domain that I can't change.

Code example:

public class Product: IEquatable<Product>
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool Equals(Product other)
    {
        if (other == null)
            return false;
        if (Id == other.Id && Name == other.Name)
            return true;
        return false;
    }
}


[TestClass]
public class ProductTest
{
    [TestMethod]
    public void Test1()
    {
        var product1 = new Product {Id = 100, Name = "iPhone"};
        var product2 = new Product {Id = 100, Name = "iPhone"};
        Assert.IsTrue(product1.Equals(product2));
    }
}

My goal is to find a quick solution to compare complex objects as structures and not implement IEquatable cause I can't extend bussiness layer. I mean something like Automapper but not to map but just to compare. Please, give some advices.

Thank in advance.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
Pavel Yermalovich
  • 1,970
  • 1
  • 15
  • 19
  • 2
    something like this? http://stackoverflow.com/questions/986572/hows-to-quick-check-if-data-transfer-two-objects-have-equal-properties-in-c/986617#986617 or: http://stackoverflow.com/questions/3060382/comparing-2-objects-and-retrive-a-list-of-fields-with-different-values/3060929#3060929 – Marc Gravell Jun 08 '11 at 09:10

1 Answers1

4

Using the code from here and here:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}


public static class ProductTest
{
    public static void Main()
    {
        var product1 = new Product { Id = 100, Name = "iPhone" };
        var product2 = new Product { Id = 100, Name = "iPhone" };
        bool x = PropertyCompare.Equal(product1, product2); // true

        var deltas = PropertyComparer<Product>.GetDeltas(product1, product2);
        // ^^= an empty list
    }
}

changing the second Name to "iPhone2" gives false and a list containing the single entry: "Name".

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900