code_junkie

How to diff Property Values of two objects using GetType GetValue?

Nov 13th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. public class Person
  2. {
  3. public String FirstName { set; get; }
  4. public String LastName { set; get; }
  5. public Role Role { set; get; }
  6. }
  7.  
  8. public class Role
  9. {
  10. public String Description { set; get; }
  11. public Double Salary { set; get; }
  12. public Boolean HasBonus { set; get; }
  13. }
  14.  
  15. public static List<String> DiffObjectsProperties(T a, T b)
  16. {
  17. List<String> differences = new List<String>();
  18. foreach (var p in a.GetType().GetProperties())
  19. {
  20. var v1 = p.GetValue(a, null);
  21. var v2 = b.GetType().GetProperty(p.Name).GetValue(b, null);
  22.  
  23. /* What happens if property type is a class e.g. Role???
  24. * How do we extract property values of Role?
  25. * Need to come up a better way than using .Namespace != "System"
  26. */
  27. if (!v1.GetType()
  28. .Namespace
  29. .Equals("System", StringComparison.OrdinalIgnoreCase))
  30. continue;
  31.  
  32. //add values to differences List
  33. }
  34.  
  35. return differences;
  36. }
  37.  
  38. public static List<String> DiffObjectsProperties(object a, object b)
  39. {
  40. Type type = a.GetType();
  41. List<String> differences = new List<String>();
  42. foreach (PropertyInfo p in type.GetProperties())
  43. {
  44. object aValue = p.GetValue(a, null);
  45. object bValue = p.GetValue(b, null);
  46.  
  47. if (p.PropertyType.IsPrimitive || p.PropertyType == typeof(string))
  48. {
  49. if (!aValue.Equals(bValue))
  50. differences.Add(
  51. String.Format("{0}:{1}!={2}",p.Name, aValue, bValue)
  52. );
  53. }
  54. else
  55. differences.AddRange(DiffObjectsProperties(aValue, bValue));
  56. }
  57.  
  58. return differences;
  59. }
  60.  
  61. var v1 = p.GetValue(a, null);
Add Comment
Please, Sign In to add comment