Many of the fundamental utility types that are heavily used in .NET programs are reliant on a correct implementation of equality to work properly. Get the implementation wrong, and things will seem to work, but they won’t be doing quite what you expect. This can have some subtle effects that lead to nasty problems. In this series, we’ll look at what those problems are and how to avoid them.

Why is Equality important in .NET?

3 Mar 2018 equality dotnet

You can get by without consideration of equality in .NET projects for quite some time without having too many problems. Eventually, however, the time comes when you have to dig into those odd problems and fix things properly.


Types of Equality

10 Mar 2018 equality dotnet

Having established the importance of equality in .NET, we can look at the different kinds of equality that you might encounter. There are three - Reference, Value and Entity equality.


Equality has Symmetry

17 Mar 2018 equality csharp

If we’re going to implement equality correctly, we need to consider the contract we’re implementing - what are the characteristics of a proper implementation of equality? The first characteristic we need to consider is symmetry.


Equality and GetHashCode

24 Mar 2018 equality dotnet

After symmetry, another aspect of the equality contract is .GetHashCode(). When you first override .Equals(object), the C# compiler will helpfully remind you that you must also override .GetHashCode().


Implementing Entity Equality

31 Mar 2018 equality dotnet

Now that we’ve talked about the importance of implementing equality, the different kinds of equality, and about the contracts required of our implementations, we can get down to actually writing some code.


Implementing Value Equality

7 Apr 2018 equality dotnet

Building on our implementation of entity equality, we are now in a position to implement value equality. This is more complex because it tends to have a greater number of factors to consider.


Types behaving badly

14 Apr 2018 equality dotnet

At the opening of this series I wrote about how a correct implementation of equality is essential for the correct behaviour of many fundamental .NET types - including List, HashSet and Dictionary. Here’s an example to show how they can break.