Roadmap › OOP Concepts in C# › Module: Relationships and Design
Lessons in this course (15)
14. Object equality, GetHashCode and ToString
IntermediateMediumLesson 14 of 15
csharp
public sealed class Money : IEquatable<Money>
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency) => (Amount, Currency) = (amount, currency);
public bool Equals(Money? other) => other is not null && Amount == other.Amount && Currency == other.Currency;
public override bool Equals(object? obj) => Equals(obj as Money);
public override int GetHashCode() => HashCode.Combine(Amount, Currency);
public override string ToString() => $"{Amount} {Currency}";
}
// Or simply: public record Money(decimal Amount, string Currency); — generates all of the aboveRule: equal objects must return equal hash codes, otherwise Dictionary/HashSet lookups fail.