2

I have two class :

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public bool isActif { get; set; }

    public Product[] Product { get; set; }
}

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

And two instances :

Customer Customer1 = new Customer
{
    FirstName = "FirstName1",
    LastName = "LastName1",
    isActif = true,
    Product = new Product[]
    {
        new Product()
        {
            Id = "1"
        }
    }
};

Customer Customer2 = new Customer
{
    FirstName = "FirstName2",
    LastName = "LastName2",
    isActif = false,
    Product = new Product[]
    {
        new Product()
        {
            Id = "2"
        }
    }
};

I have one method who compare all properties of the two instances :

But when I get to the property Product, I have an StackOverflowException generated. Why ? And how to loop the property if it's a array ?

EDIT : When I use the List there is not StackOverflowException but System.Reflection.TargetParameterCountException. How to loop the property if it's a array

1 Answers1

1

in:

foreach (PropertyInfo propertyInfo in
             objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.CanRead))

Change your where condition for:

 .Where(x => x.CanRead && x.Name != "SyncRoot")

SyncRoot documentation

If you do:

Console.WriteLine(Customer1.Product.Equals(Customer1.Product.SyncRoot));

You will see that Customer1.Product is equal to its SyncRoot property. Therefore, when you use your AreEquals method on the Product Property, you will reach the SyncRoot property, which is the same than Product Property. Then you will never be able to leave the loop. (Because SyncRoot has a SyncRoot property pointing on itself)

romain-aga
  • 1,441
  • 9
  • 14