TL ; DR:
For objects, Equals asks if two variables hold the very same object. Override Equals to compare the values instead. Override GetHashCode too, so a HashSet or a Dictionary can find equal objects.
public override bool Equals(object other) {
return other is Time t && hour == t.hour && minute == t.minute;
}
public override int GetHashCode() {
return HashCode.Combine(hour, minute);
}
Full lesson:
Two objects can hold the same values and still be two objects. Create new Time(9, 30) twice, as a and b. Then a.Equals(b) is false.
By default, Equals checks identity. It is true only when both variables hold one and the same object. So does == for a class.
Equal by value
Every class inherits Equals(object other) from object. Override it to compare the fields.
other is Time t checks that other is a Time. If it is, it names it t. Then compare t's fields with your own.
Sets need a hash code
A HashSet doesn't compare a new item with every item it holds. That would be slow. It files each object under a number, its hash code. Then it calls Equals only on objects with the same hash code.
So equal objects must have equal hash codes. GetHashCode() returns that number. HashCode.Combine(hour, minute) builds it from the same fields as Equals.
Write both
Without GetHashCode, each object keeps a different default hash code. A HashSet then never compares two equal times. It keeps both. The compiler warns you about this.
== still checks identity, unless the class also defines operator ==. Call Equals to compare values.
Your task
The Time class keeps an hour and a minute. Override Equals and GetHashCode. Two times are equal when the hour and the minute both match.
MainFunction compares three times. Then it adds them to a HashSet of alarms.
Expected output:
a and b are the same time
a and c are different times
alarms: 2Free plan: 30 tutor messages. Premium is unlimited.
