Click here to Skip to main content
15,892,575 members
Articles / Programming Languages / C#
Tip/Trick

Comparing Two Complex Objects of the Same Class

Rate me:
Please Sign up or sign in to vote.
3.47/5 (6 votes)
3 Nov 2015CPOL 25.1K   9   16
Comparing two objects of the same class using reflection and extension methods

Introduction

This tip shows how to compare two objects of the same class using reflection and extension methods.

Background

You have two objects of the same class (class contains sub classes, properties, sub classes contain properties, etc.) and you need to compare whether those two objects are the same or not. This technique doesn't need IEquals, IComparable interfaces to inherit.

Using the Code

Create a static class with the name "CompareTwoObjects" and add the below code to it:

C#
public static object  CompareEquals<T>(this T objectFromCompare, T objectToCompare)
{
   if (objectFromCompare == null && objectToCompare == null)
      return true;

   else if (objectFromCompare == null && objectToCompare != null)
      return false;

   else if (objectFromCompare != null && objectToCompare == null)
      return false;

   PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
   foreach (PropertyInfo prop in props)
      {
          object dataFromCompare = 
          objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectFromCompare, null);

          object dataToCompare = 
          objectToCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null);

          Type type = 
          objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare,null).GetType();

          if (prop.PropertyType.IsClass && 
          !prop.PropertyType.FullName.Contains("System.String"))
             {
                 dynamic convertedFromValue = Convert.ChangeType(dataFromCompare, type);
                 dynamic convertedToValue = Convert.ChangeType(dataToCompare, type);

                 object result = CompareTwoObjects.CompareEquals(convertedFromValue, convertedToValue);

                 bool compareResult = (bool)result;
                 if (!compareResult)
                    return false;
              }

          else if (!dataFromCompare.Equals(dataToCompare))
              return false;
       }

  return true;
}

This results in whether all the properties of the class and the subclasses contain the same value or not.

Usage:

C#
Object1.CompareEquals(Object2);

Points of Interest

Previously, I could see that to compare two objects, we need to implement the IEquals, IComparable interfaces and then loop through each of the properties explicitly to make sure the values are the same or not. But my code is a generic code and this is reliable and independent as well.

History

I used extension methods concept along with reflection which made it easy to compare two objects with minimal code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionType argument missing? Pin
ydude3-Nov-15 19:37
ydude3-Nov-15 19:37 
AnswerRe: Type argument missing? Pin
mppruthviraj3-Nov-15 19:45
mppruthviraj3-Nov-15 19:45 
GeneralRe: Type argument missing? Pin
#realJSOP4-Nov-15 1:53
mve#realJSOP4-Nov-15 1:53 
QuestionCheck my posted alternative Pin
#realJSOP3-Nov-15 6:03
mve#realJSOP3-Nov-15 6:03 
AnswerRe: Check my posted alternative Pin
mppruthviraj3-Nov-15 18:11
mppruthviraj3-Nov-15 18:11 
GeneralRe: Check my posted alternative Pin
Graeme_Grant4-Nov-15 5:15
mvaGraeme_Grant4-Nov-15 5:15 
GeneralRe: Check my posted alternative Pin
#realJSOP4-Nov-15 5:23
mve#realJSOP4-Nov-15 5:23 
GeneralRe: Check my posted alternative Pin
#realJSOP4-Nov-15 5:22
mve#realJSOP4-Nov-15 5:22 
QuestionAlternatively compare MD5 hashes Pin
ydude3-Nov-15 4:21
ydude3-Nov-15 4:21 
something like
C#
private static string ComputeHash(byte[] objectAsBytes)
{
    MD5 md5 = new MD5CryptoServiceProvider();
    try
    {
        byte[] result = md5.ComputeHash(objectAsBytes);

        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < result.Length; i++)
            sb.Append(result[i].ToString("X2"));

        return sb.ToString();
    }
    catch {}
}

and compare the return values
C#
var x = ComputeHash(...);
var y = ComputeHash(...);
var equal = x == y;

AnswerRe: Alternatively compare MD5 hashes Pin
#realJSOP3-Nov-15 6:01
mve#realJSOP3-Nov-15 6:01 
GeneralRe: Alternatively compare MD5 hashes Pin
ydude3-Nov-15 19:09
ydude3-Nov-15 19:09 
AnswerRe: Alternatively compare MD5 hashes Pin
mppruthviraj3-Nov-15 19:32
mppruthviraj3-Nov-15 19:32 
QuestionChecking for type String Pin
John Brett3-Nov-15 3:03
John Brett3-Nov-15 3:03 
Suggestionwhy return object? Pin
John Torjo3-Nov-15 2:13
professionalJohn Torjo3-Nov-15 2:13 
GeneralRe: why return object? Pin
mppruthviraj3-Nov-15 2:22
mppruthviraj3-Nov-15 2:22 
GeneralRe: why return object? Pin
John Torjo4-Nov-15 6:12
professionalJohn Torjo4-Nov-15 6:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.