|
| 1 | +// <PersonSample> |
| 2 | +List<Person> applicants = new List<Person>() |
| 3 | +{ |
| 4 | + new Person("Jones", "099-29-4999"), |
| 5 | + new Person("Jones", "199-29-3999"), |
| 6 | + new Person("Jones", "299-49-6999") |
| 7 | +}; |
| 8 | + |
| 9 | +// Create a Person object for the final candidate. |
| 10 | +Person candidate = new Person("Jones", "199-29-3999"); |
| 11 | +bool contains = applicants.Contains(candidate); |
| 12 | +Console.WriteLine($"{candidate.LastName} ({candidate.NationalId}) is on record: {contains}"); |
| 13 | +// The example prints the following output: |
| 14 | +// Jones (199-29-3999) is on record: True |
| 15 | +// </PersonSample> |
| 16 | + |
| 17 | +// <Person> |
| 18 | +public class Person : IEquatable<Person> |
| 19 | +{ |
| 20 | + public Person(string lastName, string ssn) |
| 21 | + { |
| 22 | + LastName = lastName; |
| 23 | + NationalId = ssn; |
| 24 | + } |
| 25 | + |
| 26 | + public string LastName { get; } |
| 27 | + |
| 28 | + public string NationalId { get; } |
| 29 | + |
| 30 | + public bool Equals(Person? other) => other is not null && other.NationalId == NationalId; |
| 31 | + |
| 32 | + public override bool Equals(object? obj) => Equals(obj as Person); |
| 33 | + |
| 34 | + public override int GetHashCode() => NationalId.GetHashCode(); |
| 35 | + |
| 36 | + public static bool operator ==(Person person1, Person person2) |
| 37 | + { |
| 38 | + if (person1 is null) |
| 39 | + { |
| 40 | + return person2 is null; |
| 41 | + } |
| 42 | + |
| 43 | + return person1.Equals(person2); |
| 44 | + } |
| 45 | + |
| 46 | + public static bool operator !=(Person person1, Person person2) |
| 47 | + { |
| 48 | + if (person1 is null) |
| 49 | + { |
| 50 | + return person2 is not null; |
| 51 | + } |
| 52 | + |
| 53 | + return !person1.Equals(person2); |
| 54 | + } |
| 55 | +} |
| 56 | +// </Person> |
0 commit comments