In an update to WilsonORWrapper, I added a method which takes two objects of the same type and compares the properties of each, returning a value reflecting the results of the comparison. Any value other than zero would indicate that at least one property on the objects are not equal.
This method may have interest to people who don’t use WilsonORWrapper, so here’s an extracted version of the code that does the comparison.
using System;
using System.Reflection;
public static class ObjectHelper
{
public static int Compare(T x, T y)
{
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public);
FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public);
int compareValue = 0;
foreach (PropertyInfo property in properties)
{
IComparable valx = property.GetValue(x, null) as IComparable;
if (valx == null)
continue;
object valy = property.GetValue(y, null);
compareValue = valx.CompareTo(valy);
if (compareValue != 0)
return compareValue;
}
foreach (FieldInfo field in fields)
{
IComparable valx = field.GetValue(x) as IComparable;
if (valx == null)
continue;
object valy = field.GetValue(y);
compareValue = valx.CompareTo(valy);
if (compareValue != 0)
return compareValue;
}
return compareValue;
}
}
With that, if you had a Name class in your code that had two properties, First and Last, you could do something like this:
Name n1 = new Name(); n1.First = "Brian"; n1.Last = "DeMarzo"; Name n2 = new Name(); n2.First = "Brian"; n2.Last = "DeMarzo"; int result1 = ObjectHelper.Compare(n1, n2); // result1 == 0 because n1 and n2 have equal properties n1.First = "Alyssa"; // change the first name, so n1 should no longer equal n2 int result2 = ObjectHelper.Compare(n1, n2); // result2 != 0 because n1 and n2 do not have equal properties
Code like this came in handy in my project where I use FileHelpers (see my blog entry from earlier today), where I was able to compare a class loaded from the database (using an O/R mapper) with a class loaded from a text file (using FileHelpers). Since the O/R mapper and FileHelpers used the same class, using this comparison method to determine if the objects were “equal” let me determine whether or not the data loaded from the database was different from the data in the text file.
Even though it used reflection, there wasn’t a huge performance hit, either. Sure beats writing manual comparison methods, which could take a while when you have a few dozen classes!
Leave a reply to Jet Cancel reply