Skip to content

Rework IEquatable<T> example #11077

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 15, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions snippets/csharp/System/IEquatableT/Equals/Equals.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
137 changes: 0 additions & 137 deletions snippets/csharp/System/IEquatableT/Equals/EqualsEx1.cs

This file was deleted.

131 changes: 0 additions & 131 deletions snippets/csharp/System/IEquatableT/Equals/EqualsEx2.cs

This file was deleted.

56 changes: 56 additions & 0 deletions snippets/csharp/System/IEquatableT/Equals/EqualsExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// <PersonSample>
List<Person> applicants = new List<Person>()
{
new Person("Jones", "099-29-4999"),
new Person("Jones", "199-29-3999"),
new Person("Jones", "299-49-6999")
};

// Create a Person object for the final candidate.
Person candidate = new Person("Jones", "199-29-3999");
bool contains = applicants.Contains(candidate);
Console.WriteLine($"{candidate.LastName} ({candidate.NationalId}) is on record: {contains}");
// The example prints the following output:
// Jones (199-29-3999) is on record: True
// </PersonSample>

// <Person>
public class Person : IEquatable<Person>
{
public Person(string lastName, string ssn)
{
LastName = lastName;
NationalId = ssn;
}

public string LastName { get; }

public string NationalId { get; }

public bool Equals(Person? other) => other is not null && other.NationalId == NationalId;

public override bool Equals(object? obj) => Equals(obj as Person);

public override int GetHashCode() => NationalId.GetHashCode();

public static bool operator ==(Person person1, Person person2)
{
if (person1 is null)
{
return person2 is null;
}

return person1.Equals(person2);
}

public static bool operator !=(Person person1, Person person2)
{
if (person1 is null)
{
return person2 is not null;
}

return !person1.Equals(person2);
}
}
// </Person>
Loading