Thursday, November 5, 2015

C sharp code to compare 2 complex objects of same type

Today I stumbled upon this code. After adding the code, you can simply compare almost 2 simple / complex objects of same type.

  1. int x = 5;  
  2. int y = 5;  
  3. XyzClass a = new XyzClass();  
  4. XyzClass b = new XyzClass();  
  5.   
  6. // Both of these should return true  
  7. bool equals = x.CompareEquals(y);  
  8. equals = a.CompareEquals(b);  
  9.   
  10. y=10;  
  11. b.Date = DateTime.Now;  
  12. b.Str="tester";  
  13.   
  14. // both of these should return false  
  15. equals = x.CompareEquals(y);  
  16. // this one should return false after finding the first non-equal property  
  17. equals = a.CompareEquals(b);  
However, I personally like the code in a comment, which is shorter than the original code. So I posted it here, as a quick reminder for you and me whenever we need that
  1. using System.IO;  
  2. using System;  
  3. using System.Reflection;  
  4.   
  5. class Program  
  6. {  
  7.     static void Main()  
  8.     {  
  9.         Console.WriteLine("Hello, World1!");  
  10.         int x = 5;  
  11.         int y = 5;   
  12.         Console.WriteLine(x.CompareEquals(y));  
  13.     }  
  14.   
  15. }  
  16.   
  17. internal static class CompareEqualsModule  
  18. {  
  19.   
  20.     public static bool CompareEquals<T>(this T objectFromCompare, T objectToCompare)  
  21.     {  
  22.   
  23.         if (objectFromCompare == null && objectToCompare == nullreturn true;  
  24.         Type fromType = objectFromCompare.GetType();  
  25.         if (fromType.IsPrimitive) return objectFromCompare.Equals(objectToCompare);  
  26.         if (fromType.FullName.Contains("System.String")) return ((objectFromCompare as string) == (objectToCompare as string));  
  27.         if (fromType.FullName.Contains("DateTime")) return DateTime.Parse(objectFromCompare.ToString()).Ticks == DateTime.Parse(objectToCompare.ToString()).Ticks;  
  28.   
  29.         foreach (PropertyInfo prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))  
  30.         {  
  31.             Type type = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null).GetType();  
  32.             object dataFromCompare = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectFromCompare, null);  
  33.             object dataToCompare = objectToCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null);  
  34.             if (CompareEquals(Convert.ChangeType(dataFromCompare, type), Convert.ChangeType(dataToCompare, type)) == falsereturn false;  
  35.         }  
  36.   
  37.         return true;  
  38.     }  
  39. }