skip to content

In C#, what do a struct's inherited ValueType.Equals and GetHashCode do, and why are they costly for a struct used as a dictionary key?

level: seniorimportance: should knowfreq 50%

answer

  1. inherited from System.ValueType
  2. bytes compared only without references
  3. reflection over fields otherwise
  4. hash from the first field
  5. override both, add IEquatable<T>

basics

~20 s

ValueType.Equals compares raw bytes only for structs without reference or floating-point fields; otherwise it reads every field through reflection, boxing as it goes. ValueType.GetHashCode then hashes only the first field, so keys differing elsewhere collide.

solid answer

~40 s

A struct that overrides neither member gets `System.ValueType`'s versions. In the .NET 10 runtime, `Equals` takes a fast path, a byte-by-byte comparison, only when the type has no reference fields, is tightly packed, has no floating-point field and does not override `Equals`; otherwise it calls `GetFields` and compares each field's value through reflection, boxing value-type fields as it reads them. On that same slow path, `GetHashCode` hashes only the first instance field. So `SensorKey(string Name, int Channel)` hashes `Name` alone: a thousand keys for one probe share one hash code, and a `HashSet<T>` or `Dictionary<TKey,TValue>` falls back to comparing them one by one. The argument to `Equals(object)` is boxed as well. Override both members, combining every field with `HashCode.Combine`, and implement `IEquatable<T>`.

code

csharp · 18 lines
csharp
var a = new SensorKey("probe-7", 1);
var b = new SensorKey("probe-7", 2);
Console.WriteLine($"Equals: {a.Equals(b)}");                             // False
Console.WriteLine($"same hash: {a.GetHashCode() == b.GetHashCode()}");   // True

var keys = new HashSet<SensorKey>();
for (int channel = 0; channel < 1000; channel++)
{
    keys.Add(new SensorKey("probe-7", channel));
}
var distinct = keys.Select(k => k.GetHashCode()).Distinct().Count();
Console.WriteLine($"{keys.Count} keys, {distinct} distinct hash code(s)");  // 1000 keys, 1

readonly struct SensorKey(string name, int channel)
{
    public string Name { get; } = name;       // a reference field: no bitwise fast path
    public int Channel { get; } = channel;    // never reaches the default hash
}

go deeper

for a junior

Remember that a struct compares by field values by default, and that overriding Equals and GetHashCode together is the normal fix.

for a middle

Explain the fast byte comparison and the reflection fallback, and why reference or floating-point fields push a struct onto the slow path.

for a senior

Diagnose a slow dictionary keyed by a struct with a string field, prove the first-field hash collision, and repair it with proper overrides and IEquatable<T>.

for a principal

Require every struct that is compared or used as a key to define its equality explicitly, and weigh record structs against hand-written members.

## What a struct inherits Every struct derives implicitly from `System.ValueType`, which overrides `object.Equals(object)` and `object.GetHashCode()` to give value types **value equality**: two instances are equal when their fields are equal, not when they are the same object. The behaviour is correct by default, which is why the cost is easy to miss. The implementation shipped in `ValueType.cs` of the .NET 10 runtime shows where the cost comes from. ## The two paths of ValueType.Equals `Equals(object obj)` first returns `false` for `null` or a different run-time type. Then it picks one of two paths: | Path | When the runtime takes it | What it does | |---|---|---| | **Fast** | the type "does not contain pointer, is tightly packed, does not have floating point number field and does not override Equals method", as the source comment puts it | compares the instance bytes directly | | **Slow** | anything else, e.g. any `string` or other reference field | calls `GetType().GetFields(...)`, then `FieldInfo.GetValue` on both instances and `Equals` on each pair | The slow path is reflection: it gets a `FieldInfo[]` array, **boxes** each value-type field that `GetValue` returns, and makes a virtual `Equals` call per field. In a quick .NET 10 run, a million default comparisons of a struct with one `string` and one `int` took many times longer than a hand-written `IEquatable<T>.Equals`. And because the parameter is `object`, the struct passed as the argument is boxed before any of this starts; where else boxing hides is the boxing lesson's subject. Floating-point fields are excluded from the fast path because bitwise and numeric equality disagree there: `0.0` and `-0.0` have different bits but are equal numbers. A struct holding one `double` therefore takes the field-by-field path, and on .NET 10 a struct holding `0.0` equals one holding `-0.0`. ## The hash code trap `GetHashCode` mixes in the type, then follows the same split. On the fast path it hashes all the instance bytes. Otherwise, as the source comment says, "we look for the first non-static field and get its hashcode" and only that one field contributes. ```csharp var keys = new HashSet<SensorKey>(); for (int ch = 0; ch < 1000; ch++) keys.Add(new SensorKey("probe-7", ch)); var distinct = keys.Select(k => k.GetHashCode()).Distinct().Count(); Console.WriteLine(distinct); // 1 readonly struct SensorKey(string name, int channel) { public string Name { get; } = name; public int Channel { get; } = channel; } ``` All thousand keys are distinct under `Equals`, but they share one hash code, so every lookup in that set walks the same chain and runs the reflective `Equals` on each entry. Swapping the declaration order of `Name` and `Channel` would make `Channel` the hashed field instead, which shows how fragile the default is. The values also feed `System.HashCode`, which is randomly seeded per process, so they change from run to run and must never be persisted. ## The repair 1. **Override `Equals(object)`** to check the type and compare the fields you mean. 2. **Override `GetHashCode`** to combine every field that `Equals` compares, for example `HashCode.Combine(Name, Channel)`. 3. **Implement `IEquatable<T>`**, so `EqualityComparer<T>.Default`, which dictionaries and sets use, calls a strongly typed `Equals(T)` without boxing. The contract between these members and the `==` operator is the lesson on equality and hashing. 4. Or declare the type a **record struct**, which synthesizes these members; that feature is covered with records. ## When the default is acceptable - The struct is never compared or hashed: it is passed around and read, nothing more. - It holds only integers or other unmanaged non-floating-point fields with no padding, so the byte comparison and the full-byte hash apply. - It is compared rarely, outside hot paths, and never used as a key. For any struct that goes into a `Dictionary<TKey,TValue>`, a `HashSet<T>` or a hot comparison loop, the design guidelines' advice to implement `IEquatable<T>` on value types is the practical rule: the default is correct but can be slow and badly distributed.

  • Why does ValueType.Equals skip the byte comparison for float and double fields?
    Because bitwise and numeric equality disagree for floating-point values: `0.0` and `-0.0` are equal numbers with different bits. The runtime's fast-path condition excludes floating-point fields, so such structs compare each field with its own `Equals`, and on .NET 10 a struct holding `0.0` equals one holding `-0.0`.
  • Is the default struct hash code stable across process runs?
    No. On .NET 10, `ValueType.GetHashCode` feeds the type identity and field data into `System.HashCode`, which uses a random seed generated per process. The values work for in-memory hash tables during one run, but never store them or send them to another process.
  • Does implementing `IEquatable<T>` alone fix the dictionary problem?
    Only half of it. `EqualityComparer<T>.Default` will call your `Equals(T)` without boxing, but the dictionary still calls `GetHashCode`, and the inherited first-field hash still collides. Implement `IEquatable<T>`, override `Equals(object)` and override `GetHashCode` together.

  • A struct's default Equals compares references, like a class.
  • The default GetHashCode of a struct combines every field.
  • Structs compare by value, so the default equality is always fast.
  • Implementing IEquatable<T> is enough; GetHashCode can stay inherited.
  • Default struct hash codes are stable, so they can be saved to a database.