When you define value equality for a type, you typically compare all fields in the two instances to determine whether they are equivalent. You can also use just a subset of the fields in the comparison.
Below, two Programmer instances are equivalent if their Name and Age properties match. But their Mood properties are not used in the comparison.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| public class Programmer{ public string Name { get; set; } public int Age { get; set; } public string Mood { get; set; } // constructor omitted public static bool operator ==(Programmer p1, Programmer p2) { return (p1.Name == p2.Name) && (p1.Age == p2.Age); } public static bool operator !=(Programmer p1, Programmer p2) { return !(p1 == p2); }} |
Test results:
1
2
3
4
5
6
| Programmer p1 = new Programmer("Sean", 47, "Elated");Programmer p2 = new Programmer("Sean", 47, "Surly");Programmer p3 = new Programmer("Bob", 47, "Surly");bool check = (p1 == p2); // truecheck = (p2 == p3); // false |

