coder, gamer, parent
In: C#|Reflection
9 Jul 2010Here’s a helper that will allow you to compare 2 objects using reflection.
Note: that this will also go through the objects base class and compare the base class fields and properties. I found it necessary to do this, however for speed you may want to add BindingFlags.DeclaredOnly to type.GetProperties() and type.GetFields() to limit the depth of the comparison.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public static class Helper<T> { public static bool Compare(T x, T y) { var type = typeof(T); var properties = type.GetProperties(); var fields = type.GetFields(); foreach (var p in properties) { var valueOfX = p.GetValue(x, null) as IComparable; if (valueOfX == null) continue; var valueOfY = p.GetValue(y, null); if (valueOfX .CompareTo(valueOfY) != 0) return false; } foreach (var f in fields) { var valueOfX = f.GetValue(x) as IComparable; if (valueOfX == null) continue; var valueOfY = f.GetValue(y); if (valueOfX.CompareTo(valueOfY) != 0) return false; } return true; } } |
A real world class
1 2 3 4 5 6 7 8 9 10 11 12 | public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public Customer(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } (...) } |
How to use the Helper
1 2 3 4 5 6 7 8 9 10 11 | var customer1 = new Customer("Justin", "Shield"); var customer2 = customer1; // Helper will return true as all of the fields in customer 1 is equal to all of the fields in customer 2 Assert.IsTrue(Helper<Customer>.Compare(customer1, customer2), "Customer 1 is not equal to customer 2"); var customer3 = new Customer("Belinda", "Shield"); // Helper will return false as all of the fields in customer 1 is not equal to all of the fields in customer 3 Assert.IsFalse(Helper<Customer>.Compare(customer1, customer3), "Customer 1 is equal to customer 3"); |
Justin is a Senior Software Engineer living in Brisbane. A Polyglot Developer proficient in multiple programming languages including [C#, C/C++, Java, Android, Ruby..]. He's currently taking an active interest in Teaching Kids to Code, Functional Programming, Robotics, 3D Printers, RC Quad-Copters and Augmented Reality.
Software Engineering is an art form, a tricky art form that takes as much raw talent as it does technical know how. I'll be posting articles on professional tips and tricks, dos and donts, and tutorials.