How do I check if an object is equal to a new object of the same class?

Viewed 32075

If I have a object like:

public class Person
{
    public int id {get;set;}
    public string name {get;set;}
}

And I want the behavior:

Person a = new Person();
Person b = new Person();

a == b;

and that a == b returns true, do I have to override the Object.Equals() method? or is there some other way of doing it without overriding the Equals method?

EDIT

I want to compare data, as I want to know if a external method that I call returns a new object or a object with different data than a new object

8 Answers

If you want you can write an extention methode like this (make a new class like this) :

public static class Extensions
{
    public static bool IsEqual<T>(this T objA, T objB)
        {
            foreach (var item in objA.GetType().GetProperties())
            {
                if (item.GetValue(objA).ToString() != item.GetValue(objB).ToString()) 
                    return false;
            }

            return true;
        }
    }
}

Then you can use this extention methode something like this :

Person a = new Person { id = 1, name = "person1" };
Person b = new Person { id = 1, name = "person1" };
....
if ( a.IsEqual<Person>(b)) // this returns true ;) 
{
     do something ...
}
else 
{
    do something else ...
}
....

Enjoy it.

In C# 9.0 and above, there is a new type called record whose equality is value-based. So you can define it like:

public record Person
{
    public string LastName { get; }
    public string FirstName { get; }

    public Person(string first, string last) => (FirstName, LastName) = (first, last);
}

Then you can use

var bill1 = new Person("Bill", "Wagner");
var bill2 = new Person("Bill", "Wagner");

Console.WriteLine(bill1 == bill2); // true

Reference: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#record-types

Related