I have a couple of complex objects that I’d like to compare properties on. The following code does a fine job, up until you get to a collection. I’d like to recursively call the function with each member of the collection. Can someone take a look and help me to determine the type of object in the collection so that I can call HasPropertyChanged again?
This pseudocode shows my intent
if (p.GetType() == typeof(System.Collections.Generic.List<>))
{
foreach (var blah in //the list)
{
HasPropertyChanged<//TheType>(Type obj1, Type obj2, null);
}
}
Also, this part of the code bugs me. If I don’t call the tostring method, I’ll get some funky results, like id 63633 not equaling 63633
object val1 = Original.GetType().GetProperty(p.Name).GetValue(Original, null);
object val2 = Modified.GetType().GetProperty(p.Name).GetValue(Modified, null);
if (!IgnoreProperties.Contains(p.Name) &&
val1 != null && val2 != null &&
val1.ToString() != val2.ToString())
{
return true;
}
Here it is in it’s entirety.
private bool HasPropertyChanged<T>(T Original, T Modified, string[] IgnoreProperties)
{
if (Original == null || Modified == null)
return false;
if (IgnoreProperties == null)
IgnoreProperties = new string[] { };
IEnumerable<PropertyInfo> properties = typeof(T).GetProperties();
foreach (var p in properties)
{
if (p.GetType() == typeof(System.Collections.Generic.List<>))
{
foreach (var blah in //the list)
{
HasPropertyChanged<//TheType>(Type obj1, Type obj2, null);
}
}
object val1 = Original.GetType().GetProperty(p.Name).GetValue(Original, null);
object val2 = Modified.GetType().GetProperty(p.Name).GetValue(Modified, null);
if (!IgnoreProperties.Contains(p.Name) &&
val1 != null && val2 != null &&
val1.ToString() != val2.ToString())
{
return true;
}
}
return false;
}
Since you’re dealing with types at runtime, you should have a non-generic version of your function which takes a
Typeparameter:With that, you can call the method for the list elements: