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.

int x = 5;
int y = 5;
XyzClass a = new XyzClass();
XyzClass b = new XyzClass();

// Both of these should return true
bool equals = x.CompareEquals(y);
equals = a.CompareEquals(b);

y=10;
b.Date = DateTime.Now;
b.Str="tester";

// both of these should return false
equals = x.CompareEquals(y);
// this one should return false after finding the first non-equal property
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
using System.IO;
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World1!");
        int x = 5;
        int y = 5; 
        Console.WriteLine(x.CompareEquals(y));
    }

}

internal static class CompareEqualsModule
{

    public static bool CompareEquals<T>(this T objectFromCompare, T objectToCompare)
    {

        if (objectFromCompare == null && objectToCompare == null) return true;
        Type fromType = objectFromCompare.GetType();
        if (fromType.IsPrimitive) return objectFromCompare.Equals(objectToCompare);
        if (fromType.FullName.Contains("System.String")) return ((objectFromCompare as string) == (objectToCompare as string));
        if (fromType.FullName.Contains("DateTime")) return DateTime.Parse(objectFromCompare.ToString()).Ticks == DateTime.Parse(objectToCompare.ToString()).Ticks;

        foreach (PropertyInfo prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            Type type = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null).GetType();
            object dataFromCompare = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectFromCompare, null);
            object dataToCompare = objectToCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null);
            if (CompareEquals(Convert.ChangeType(dataFromCompare, type), Convert.ChangeType(dataToCompare, type)) == false) return false;
        }

        return true;
    }
}

No comments:

Post a Comment