Click here to Skip to main content
15,925,206 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.5K   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
professional#realJSOP4-Nov-15 1:53 
QuestionCheck my posted alternative Pin
#realJSOP3-Nov-15 6:03
professional#realJSOP3-Nov-15 6:03 
AnswerRe: Check my posted alternative Pin
mppruthviraj3-Nov-15 18:11
mppruthviraj3-Nov-15 18:11 
Hi John,

I just checked your post but I found that in one of the case you code failed to return the correct result.

Consider the code below.


C#
public class TestClass2
        {

            public int w { get; set; }
            public int z { get; set; }
        }

        public class TestClass
        {
            public int x { get; set; }

            public TestClass2 testClassOneMore { get; set; }
            public int y { get; set; }

        }
        public static void Main(string[] args)
        {
            TestClass tc1 = new TestClass();
            tc1.x = 2;
            tc1.y = 2;
            TestClass2 testClass2 = new TestClass2();
            testClass2.w = 7;
            testClass2.z = 7;
            tc1.testClassOneMore = testClass2;



            TestClass tc2 = new TestClass();
            tc2.x = 2;
            tc2.y = 2;
            TestClass2 testClass3 = new TestClass2();
            testClass3.w = 7;
            testClass3.z = 7;
            tc2.testClassOneMore = testClass3;

            object result = tc1.CompareEquals(tc2);
        }



As you can see all the properties of the class and the subclass is having the same values so it should return true. But when I debug using VS 2013 I found that this is returning false. May be the code you wrote should be extended or some modification should be done.

Thank you so much for some inputs.After reading your article I may also need to do some modifications to my code.

Thank you
Pruthviraj
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
professional#realJSOP4-Nov-15 5:23 
GeneralRe: Check my posted alternative Pin
#realJSOP4-Nov-15 5:22
professional#realJSOP4-Nov-15 5:22 
QuestionAlternatively compare MD5 hashes Pin
ydude3-Nov-15 4:21
ydude3-Nov-15 4:21 
AnswerRe: Alternatively compare MD5 hashes Pin
#realJSOP3-Nov-15 6:01
professional#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.