I have a class named 'Clock' that implements the IEquatable interface. I've implemented the 'Equals' method in my class to compare two objects like this:
public bool Equals(Clock? other)
{
return _hours == other?._hours && _minutes == other._minutes;
}
When I changed my class to a record type and replaced the Equals method with the == operator, the results remained the same. Can I conclude that the Equals method in my class essentially performs the same comparison as the == operator does for record types?
Scenario one:
I have two objects of Clock class like this and want to check value equality of two objects using Equals method which I added to my class.
Clock clock1 = new(2, 10);
Clock clock2 = new(2, 10);
if (clock2.Equals(clock1))
{
Console.WriteLine("Equal");
}
Second scenario: changing my class to record type and comparing two objects with == operator
Clock clock1 = new(2, 10);
Clock clock2 = new(2, 10);
if (clock1 == clock2)
{
Console.WriteLine("Equal");
}
In the both cases they return true. I wonder does Equals method does exact same thing as == ?
Yes, with a few basic assumptions,
==for a record is the same as theEqualsyou wrote. From the proposal for records,Your
Clock.Equalssatisfy the conditions for the synthesisedEqualsto return true if we assume a few basic things, such as:_hoursand_minutesare the only fields ofClock_hoursand_minutesareints, or anything such that the default equality comparer for that type returns the same thing as comparing them with==.Clockdoesn't have derived records (EqualityContractwill always be equal)