Skip to content

Commit 0fba810

Browse files
authored
Rework IEquatable<T> example (#11077)
1 parent 2427e62 commit 0fba810

File tree

15 files changed

+205
-844
lines changed

15 files changed

+205
-844
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
</Project>

snippets/csharp/System/IEquatableT/Equals/EqualsEx1.cs

-137
This file was deleted.

snippets/csharp/System/IEquatableT/Equals/EqualsEx2.cs

-131
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)