Last active
May 12, 2025 13:26
-
-
Save marcominerva/4fe3847ba4b80002dfa9c00dd84dd7f9 to your computer and use it in GitHub Desktop.
Equality operator for C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Person : IEquatable<Person> | |
{ | |
public required string FirstName { get; set; } | |
public required string LastName { get; set; } | |
public bool Equals(Person? other) | |
{ | |
if (other is null) | |
{ | |
return false; | |
} | |
return FirstName == other.FirstName && LastName == other.LastName; | |
} | |
public override bool Equals(object? obj) | |
=> obj is Person person && Equals(person); | |
public override int GetHashCode() | |
=> HashCode.Combine(FirstName, LastName); | |
public static bool operator ==(Person? left, Person? right) | |
=> ReferenceEquals(left, right) || EqualityComparer<Person>.Default.Equals(left, right); | |
public static bool operator !=(Person? left, Person? right) | |
=> !(left == right); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment