✨ Shield now has support for Avalonia UI

How to compare two objects in C#: A Guide for Developers

May 24, 2024 | C#

In this article, we’ll walk through how to create a generic method that can compare the objects of any class, even those with nested collections. We’ll break it down step by step so you can implement this in your projects effortlessly.

Introduction

Comparing objects in C# can be straightforward when dealing with primitive properties, but what happens when your objects contain collections like lists? We’ll create a robust solution for comparing objects of any class, including those with nested collections. We’ll cover:

  • How to set up the project.
  • Writing a generic compare method.
  • Testing the compare method with complex objects.

This guide is perfect for you if you’ve ever struggled with object comparisons and are looking for a reusable solution.

Setting Up the Project

Before diving into the comparison logic, let’s set up our project. We’ll create a console application where we’ll define classes like Employee, Department, Student, and Course.

Creating the Necessary Classes

First, fire up Visual Studio and create a new Console Application called ObjectComparisonDemo. Then, add the following classes to your project: Employee, Department, Student, and Course.

using System;

using System.Collections.Generic;



public class Employee

{

    public int EmpId { get; set; }

    public string EmpName { get; set; }

    public int EmpAge { get; set; }

    public DateTime JoiningDate { get; set; }

    public List<Department> EmpDepartment { get; set; }

}



public class Department

{

    public int DeptId { get; set; }

    public string DeptName { get; set; }

}



public class Student

{

    public int StudentId { get; set; }

    public string StudentName { get; set; }

    public DateTime JoiningDate { get; set; }

    public List<Course> StudentCourse { get; set; }

}



public class Course

{

    public int CourseId { get; set; }

    public string CourseName { get; set; }

}

These classes have properties that will help us demonstrate our comparison method.

Building the Compare Method

Now comes the interesting part: building the generic compare method. This method will compare the properties of two objects, including nested collections.

How the Compare Method Works

The compare method will iterate through each property of the two objects. If it encounters a collection, it will recursively compare each item in the list. Here’s how it looks:

using System.Reflection;



public static class CompareObject

{

    public static bool Compare<T>(T e1, T e2)

    {

        foreach (PropertyInfo propObj1 in e1.GetType().GetProperties())

        {

            var propObj2 = e2.GetType().GetProperty(propObj1.Name);

            if (propObj1.PropertyType.Name.Equals("List`1"))

            {

                dynamic objList1 = propObj1.GetValue(e1, null);

                dynamic objList2 = propObj2.GetValue(e2, null);



                if (objList1.Count != objList2.Count) return false;



                for (int i = 0; i < objList1.Count; i++)

                {

                    if (!Compare(objList1[i], objList2[i])) return false;

                }

            }

            else

            {

                if (!propObj1.GetValue(e1, null).Equals(propObj2.GetValue(e2, null)))

                    return false;

            }

        }

        return true;

    }

}

This method uses reflection to iterate through properties and handles collections by invoking itself recursively. Efficient, right?

Putting It All Together

With our classes and compare method ready, let’s create some test objects and put our method to the test.

Example Use Case: Comparing Employees and Students

Let’s create some Employee and Student objects and compare them:

public class Program

{

    public static void Main(string[] args)

    {

        Employee e1 = new Employee

        {

            EmpId = 1,

            EmpName = "John Doe",

            EmpAge = 30,

            JoiningDate = DateTime.Now,

            EmpDepartment = new List<Department>

            {

                new Department { DeptId = 101, DeptName = "HR" },

                new Department { DeptId = 102, DeptName = "IT" }

            }

        };



        Employee e2 = new Employee

        {

            EmpId = 1,

            EmpName = "John Doe",

            EmpAge = 30,

            JoiningDate = DateTime.Now,

            EmpDepartment = new List<Department>

            {

                new Department { DeptId = 101, DeptName = "HR" },

                new Department { DeptId = 102, DeptName = "IT" }

            }

        };



        bool areEmployeesEqual = CompareObject.Compare(e1, e2);

        Console.WriteLine("Are Employees Equal? " + areEmployeesEqual); // Should print 'True'



        Student s1 = new Student

        {

            StudentId = 1001,

            StudentName = "Alice Smith",

            JoiningDate = DateTime.Now,

            StudentCourse = new List<Course>

            {

                new Course { CourseId = 1, CourseName = "Math" },

                new Course { CourseId = 2, CourseName = "Science" }

            }

        };



        Student s2 = new Student

        {

            StudentId = 1001,

            StudentName = "Alice Smith",

            JoiningDate = DateTime.Now,

            StudentCourse = new List<Course>

            {

                new Course { CourseId = 1, CourseName = "Math" },

                new Course { CourseId = 2, CourseName = "Science" }

            }

        };



        bool areStudentsEqual = CompareObject.Compare(s1, s2);

        Console.WriteLine("Are Students Equal? " + areStudentsEqual); // Should print 'True'

    }

}

We’ve created two Employee objects and two Student objects. Our compare method will check if they are equal, and it should print True for both comparisons.

Conclusion

Comparing complex objects in C# doesn’t have to be a nightmare. With a little bit of reflection and recursion, you can create a robust method to handle all the tedious tasks.

Benefits Recap:

  • Simplicity: Easily compare complex objects with nested collections.
  • Flexibility: Applicable to any class type.
  • Efficiency: Reusable method for multiple use cases.

Don’t wait! Implement this today and make your code a whole lot simpler!

You May Also Like