I'm attempting write a generic method to do memberwise compare on user defined objects which potentially (almost always) have several levels of nesting. I'm working off of the example found here with one little twist; if the property cannot be compared with the equality operator (those in the pTypes array), then I want to make a recursive call passing in the current properties. The code I have will not compile, I've tried various syntax in the recursive call and I'm simply wondering what is the correct syntax? Or can you do this at all?
Here is my method as of now;
public static string[] MemberWiseCompare<T>(T act, T exp) where T : ICommonObject
{
List<string> errors = new List<string>();
if (act != null && exp != null)
{
Type[] pTypes = { typeof(int), typeof(bool), typeof(string), typeof(float), typeof(double), typeof(DateTime) };
Type type = typeof(T);
foreach (PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (pTypes.Contains(pi.PropertyType))
{
if (type.GetProperty(pi.Name).GetValue(act, null) != type.GetProperty(pi.Name).GetValue(exp, null))
{
errors.Add(pi.Name);
}
}
else
{
string[] innerErrors = MemberWiseCompare<pi.PropertyType>(pi.GetValue(act, null), pi.GetValue(exp, null));
}
}
}
return null;
}
Of course there are other parts of the method which I've yet to implement (aggregating the errors at the bottom of the function and returning something other than null) but for the time being I'm only concerned with getting the recursive MemberWiseCompare
to work. From there I can figure out the rest. I think I have some problem understanding what the compiler is taking away from the type I specify for the generic ( ie pi.PropertyType ). I figured that would work because it's providing the type we'll be using in the generic call. I'm also anticipating some problems with it boxing my values so that GetValue
returns an object
rather than the more specific type.
EDIT: The compiler error is the good old "best overloaded method has some invalid args"