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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.