Search code examples
c#icomparable

compare objects for equality - if the values of the properties are the same


I don't use is so often. So that is why I ask this question.

But apparently it is not possible in C# to just do a simple comparison with objects. So of course I googled first, but I only found very redundant solutions. And I know that you can can by javascript serialize the objects and then back to strings and then compare the properties with each other.

Because I just want to compare two simple objects - if the value of the properties are the same. So I have this:

public class Person
{

    public string FirstName { get; set; }
    public string LastName { get; set; }   


    public Person()
    {
    }

    public bool IsEqualTo(Person compareTo)
    {
        return (FirstName == compareTo.FirstName && LastName == compareTo.LastName);
    }

 public static bool AreEqual<AnyType>(AnyType mass1, AnyType mass2) where AnyType : IComparable<AnyType>
        {
            return mass1.CompareTo(mass2) == 0;
        }


    public Person(string lastName, string firstName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }  
}

But then I can't use the AreEqual method like this:

var person = new Person("Niels","Engelen");
var person99 = new Person("Niels", "Engelen")

 var equals = Person.AreEqual(person,  person99);

And so:

 var equals = person.CompareTo(person99);

This of course doesn't work.

So only this works then?

 public bool IsEqualTo(Person compareTo)
    {
        return (FirstName == compareTo.FirstName && LastName == compareTo.LastName);
    }

Than the output of:

   var equals = person.IsEqualTo(person99);

will be true.

But then you have to compare every property.

So is there no short method for comparing objects?

Thank you.

Very strange that in such a huge language like C# you don't have a method where you can compare Objects for equality.

I searched some more and I found that you do it with records:

var record1 = new Person.Hello("Niels", "Engelen");
var record2 = new Person.Hello("Niels", "Engelen");

var equalRecords = record1 == record2;
Console.WriteLine("Records " +  equalRecords);

Even in Javascript you can compare complex objects the easy way.


Solution

  • You can use reflection to loop over all properties of your class and compare them:

    public bool IsEqualTo(Person other)
        {
            foreach(var prop in typeof(Person).GetProperties())
            {
                var value1 = prop.GetValue(this);
                var value2 = prop.GetValue(other);
                if(!value1.Equals(value2))
                {
                    return false;
                }
            }
            return true;
        }
    

    If you add or remove any properties, you won't have to modify your IsEqualTo method. The downside of this approach is that refelction has typically a low performance. If you do a lot of comparisions, this might not be a good solutions.