-
Notifications
You must be signed in to change notification settings - Fork 6k
Improve C# value equality documentation with enhanced content and structured code examples #48073
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
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d549251
Initial plan
Copilot 1d04c41
Add comprehensive documentation improvements for polymorphic equality…
Copilot cc68c6a
Add AI-usage metadata and finalize documentation improvements
Copilot 4678856
Address PR feedback: fix AI metadata, improve records section, and cl…
Copilot a68ef72
Apply suggestions from code review
BillWagner d2220e0
Apply suggestions from code review
BillWagner 28f69b7
Address PR feedback: fix documentation content and break up long code…
Copilot f07fdda
Add introductory sentences before consecutive code blocks to improve …
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
144 changes: 144 additions & 0 deletions
144
...rators/snippets/how-to-define-value-equality-for-a-type/RecordCollectionsIssue/Program.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
namespace RecordCollectionsIssue; | ||
|
||
// <ProblemExample> | ||
// Records with reference-equality members don't work as expected | ||
public record PersonWithHobbies(string Name, List<string> Hobbies); | ||
// </ProblemExample> | ||
|
||
// <SolutionExample> | ||
// A potential solution using IEquatable<T> with custom equality | ||
public record PersonWithHobbiesFixed(string Name, List<string> Hobbies) : IEquatable<PersonWithHobbiesFixed> | ||
{ | ||
public virtual bool Equals(PersonWithHobbiesFixed? other) | ||
{ | ||
if (ReferenceEquals(null, other)) return false; | ||
if (ReferenceEquals(this, other)) return true; | ||
|
||
// Use SequenceEqual for List comparison | ||
return Name == other.Name && Hobbies.SequenceEqual(other.Hobbies); | ||
} | ||
|
||
public override int GetHashCode() | ||
{ | ||
// Create hash based on content, not reference | ||
var hashCode = new HashCode(); | ||
hashCode.Add(Name); | ||
foreach (var hobby in Hobbies) | ||
{ | ||
hashCode.Add(hobby); | ||
} | ||
return hashCode.ToHashCode(); | ||
} | ||
} | ||
// </SolutionExample> | ||
|
||
// <OtherTypes> | ||
// These also use reference equality - the issue persists | ||
public record PersonWithHobbiesArray(string Name, string[] Hobbies); | ||
|
||
public record PersonWithHobbiesImmutable(string Name, IReadOnlyList<string> Hobbies); | ||
// </OtherTypes> | ||
|
||
// <MainProgram> | ||
class Program | ||
{ | ||
static void Main(string[] args) | ||
{ | ||
// <ProblemDemonstration> | ||
Console.WriteLine("=== Records with Collections - The Problem ==="); | ||
|
||
// Problem: Records with mutable collections use reference equality for the collection | ||
var person1 = new PersonWithHobbies("Alice", [ "Reading", "Swimming" ]); | ||
var person2 = new PersonWithHobbies("Alice", [ "Reading", "Swimming" ]); | ||
|
||
Console.WriteLine($"person1: {person1}"); | ||
Console.WriteLine($"person2: {person2}"); | ||
Console.WriteLine($"person1.Equals(person2): {person1.Equals(person2)}"); // False! Different List instances | ||
Console.WriteLine($"Lists have same content: {person1.Hobbies.SequenceEqual(person2.Hobbies)}"); // True | ||
Console.WriteLine(); | ||
// </ProblemDemonstration> | ||
|
||
// <SolutionDemonstration> | ||
Console.WriteLine("=== Solution 1: Custom IEquatable Implementation ==="); | ||
|
||
var personFixed1 = new PersonWithHobbiesFixed("Bob", [ "Cooking", "Hiking" ]); | ||
var personFixed2 = new PersonWithHobbiesFixed("Bob", [ "Cooking", "Hiking" ]); | ||
|
||
Console.WriteLine($"personFixed1: {personFixed1}"); | ||
Console.WriteLine($"personFixed2: {personFixed2}"); | ||
Console.WriteLine($"personFixed1.Equals(personFixed2): {personFixed1.Equals(personFixed2)}"); // True! Custom equality | ||
Console.WriteLine(); | ||
// </SolutionDemonstration> | ||
|
||
// <ArrayExample> | ||
Console.WriteLine("=== Arrays Also Use Reference Equality ==="); | ||
|
||
var personArray1 = new PersonWithHobbiesArray("Charlie", ["Gaming", "Music" ]); | ||
var personArray2 = new PersonWithHobbiesArray("Charlie", ["Gaming", "Music" ]); | ||
|
||
Console.WriteLine($"personArray1: {personArray1}"); | ||
Console.WriteLine($"personArray2: {personArray2}"); | ||
Console.WriteLine($"personArray1.Equals(personArray2): {personArray1.Equals(personArray2)}"); // False! Arrays use reference equality too | ||
Console.WriteLine($"Arrays have same content: {personArray1.Hobbies.SequenceEqual(personArray2.Hobbies)}"); // True | ||
Console.WriteLine(); | ||
// </ArrayExample> | ||
|
||
// <ImmutableExample> | ||
Console.WriteLine("=== Same Issue with IReadOnlyList ==="); | ||
|
||
var personImmutable1 = new PersonWithHobbiesImmutable("Diana", [ "Art", "Travel" ]); | ||
var personImmutable2 = new PersonWithHobbiesImmutable("Diana", [ "Art", "Travel" ]); | ||
|
||
Console.WriteLine($"personImmutable1: {personImmutable1}"); | ||
Console.WriteLine($"personImmutable2: {personImmutable2}"); | ||
Console.WriteLine($"personImmutable1.Equals(personImmutable2): {personImmutable1.Equals(personImmutable2)}"); // False! Reference equality | ||
Console.WriteLine($"Content is the same: {personImmutable1.Hobbies.SequenceEqual(personImmutable2.Hobbies)}"); // True | ||
Console.WriteLine(); | ||
// </ImmutableExample> | ||
|
||
Console.WriteLine("=== Collection Behavior Summary ==="); | ||
Console.WriteLine("Type | Equals Result | Reason"); | ||
Console.WriteLine("----------------------------------|---------------|------------------"); | ||
Console.WriteLine($"Record with List<T> | {person1.Equals(person2),-13} | Reference equality"); | ||
Console.WriteLine($"Record with custom IEquatable<T> | {personFixed1.Equals(personFixed2),-13} | Custom equality logic"); | ||
Console.WriteLine($"Record with Array | {personArray1.Equals(personArray2),-13} | Reference equality"); | ||
Console.WriteLine($"Record with IReadOnlyList<T> | {personImmutable1.Equals(personImmutable2),-13} | Reference equality"); | ||
|
||
Console.WriteLine("\nPress any key to exit."); | ||
Console.ReadKey(); | ||
} | ||
} | ||
// </MainProgram> | ||
|
||
/* Expected Output: | ||
=== Records with Collections - The Problem === | ||
person1: PersonWithHobbies { Name = Alice, Hobbies = System.Collections.Generic.List`1[System.String] } | ||
person2: PersonWithHobbies { Name = Alice, Hobbies = System.Collections.Generic.List`1[System.String] } | ||
person1.Equals(person2): False | ||
Lists have same content: True | ||
|
||
=== Solution 1: Custom IEquatable Implementation === | ||
personFixed1: PersonWithHobbiesFixed { Name = Bob, Hobbies = System.Collections.Generic.List`1[System.String] } | ||
personFixed2: PersonWithHobbiesFixed { Name = Bob, Hobbies = System.Collections.Generic.List`1[System.String] } | ||
personFixed1.Equals(personFixed2): True | ||
|
||
=== Arrays Also Use Reference Equality === | ||
personArray1: PersonWithHobbiesArray { Name = Charlie, Hobbies = System.String[] } | ||
personArray2: PersonWithHobbiesArray { Name = Charlie, Hobbies = System.String[] } | ||
personArray1.Equals(personArray2): False | ||
Arrays have same content: True | ||
|
||
=== Same Issue with IReadOnlyList === | ||
personImmutable1: PersonWithHobbiesImmutable { Name = Diana, Hobbies = System.String[] } | ||
personImmutable2: PersonWithHobbiesImmutable { Name = Diana, Hobbies = System.String[] } | ||
personImmutable1.Equals(personImmutable2): False | ||
Content is the same: True | ||
|
||
=== Collection Behavior Summary === | ||
Type | Equals Result | Reason | ||
----------------------------------|---------------|------------------ | ||
Record with List<T> | False | Reference equality | ||
Record with custom IEquatable<T> | True | Custom equality logic | ||
Record with Array | False | Reference equality | ||
Record with IReadOnlyList<T> | False | Reference equality | ||
*/ |
10 changes: 10 additions & 0 deletions
10
...-to-define-value-equality-for-a-type/RecordCollectionsIssue/RecordCollectionsIssue.csproj
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
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> | ||
BillWagner marked this conversation as resolved.
Show resolved
Hide resolved
BillWagner marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
</PropertyGroup> | ||
|
||
</Project> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.