Back to search
Generator.Equals
SkillGitHub
A source code generator for automatically implementing IEquatable<T> using only attributes.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Checked today
Badge for your README
Markdown
[](/listings/diegofrata--generator-equals)HTML
<a href="/listings/diegofrata--generator-equals"><img src="/api/listings/diegofrata--generator-equals/badge.svg" alt="findsafeskills safety rating" /></a>Install
i
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Simply add the package `Generator.Equals` to your project. Keep reading to learn how to add the attributes to your types.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 558 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- [](https://www.nuget.org/packages/Generator.Equals/)
- # Generator.Equals
- A C# source generator that automatically implements `IEquatable<T>`, `Equals`, and `GetHashCode` — using just attributes.
- Writing correct equality logic in C# is tedious, error-prone, and easy to forget when adding new properties. Generator.Equals eliminates that boilerplate by generating efficient, best-practice equality code at compile time.
- ### Why use Generator.Equals?
- - **Zero boilerplate** — Mark your type with `[Equatable]` and the generator does the rest. No hand-written `Equals`, `GetHashCode`, or `==`/`!=` operators.
- - **Collection-aware** — Compare arrays, lists, dictionaries, and sets by value out of the box with `[OrderedEquality]`, `[UnorderedEquality]`, and `[SetEquality]`.
- - **Highly customizable** — Use `[CustomEquality]`, `[StringEquality]`, `[PrecisionEquality]`, `[ReferenceEquality]`, or `[IgnoreEquality]` to control comparison per-property.
- - **Works everywhere** — Supports classes, structs, records, and record structs.
- - **Inheritance-friendly** — Correctly chains `base.Equals()` across deep inheritance hierarchies and inherits equality attributes from overridden properties.
- - **Structured diffs** — Call `Inequalities()` to get exactly which members differ between two instances, with full paths into nested objects, collections, and dictionaries.
- - **Compile-time only** — No reflection or IL injection. The generator emits plain C# source code that you can inspect and debug.
- ----------------
- ## Requirements
- In order to use this library, you must:
- * Use a target framework that supports .NET Standard >= 2.0
- * Set your project's C# ```LangVersion``` property to 9.0 or higher.
- ## Installation
- Simply add the package `Generator.Equals` to your project. Keep reading to learn how to add the attributes to your types.
- ## Usage
- The below sample shows how to use Generator.Equals to override the default equality implementation for a C# record, enhancing it with the ability to determine the equality between the array contents of the record.
- ```c#
- using Generator.Equals;
- [Equatable]
- partial record MyRecord(
- [property: OrderedEquality] string[] Fruits
- );
- class Program
- {
- static void Main(string[] args)
- {
- var record1 = new MyRecord(new[] {"banana", "apple"});
- var record2 = new MyRecord(new[] {"banana", "apple"});
- var record3 = new MyRecord(new[] {"banana", "cherry"});
- // Use the generated == operator
- Console.WriteLine(record1 == record2); // True
- // Use the generated comparer directly
- Console.WriteLine(MyRecord.EqualityComparer.Default.Equals(record1, record3)); // False
- // List exactly which members differ between two instances
- foreach (var diff in MyRecord.EqualityComparer.Default.Inequalities(record1, record3))
- Console.WriteLine(diff);
- // Output:
- // Fruits[1]: apple → cherry
- }
- }
- ```
- Need more than records? Generator.Equals supports properties (and fields) also across classes, structs and record structs.
- ```c#
- using Generator.Equals;
- [Equatable]
- partial class MyClass
- {
- [DefaultEquality]
- private int _secretNumber = 42;
- [OrderedEquality]
- public string[] Fruits { get; set; }
- }
- [Equatable]
- partial struct MyStruct
- {
- [OrderedEquality]
- public string[] Fruits { get; set; }
- }
- [Equatable]
- partial record struct MyRecordStruct(
- [property: OrderedEquality] string[] Fruits
- );
- ```
- ## Supported Comparers
- Below is a list of all supported comparers. Would you like something else added? Let me know by raising an issue or sending a PR!
- ### Default
- This is the comparer that's used when a property has no attributes indicating otherwise. The generated code will use
- ```EqualityComparer<T>.Default``` for both equals and hashing operation.
- > _Fields are opt-in: they are **not** compared unless explicitly annotated. To include a field, annotate it with `DefaultEquality` (or any other equality attribute). Properties are compared by default. See [Migrating from version 4](#migrating-from-version-4)._
- ### IgnoreEquality
- ```c#
- [IgnoreEquality]
- public string Name { get; set; }
- ```
- As the name implies, the property is ignored during Equals and GetHashCode calls!
- ### OrderedEquality
- ```c#
- [OrderedEquality]
- public string[] Fruits { get; set; } // Fruits have to be in the same order for the array to be considered equal.
- ```
- This equality comparer will compare properties as a sequence instead of a reference. This works just like ```Enumerable.SequenceEqual```, which assumes both lists are of the same size and same sort.
- Bear in mind that the property has to implement IEnumerable<T> and the that the items themselves implement equality (you can use Generator.Equals in the items too!).
- You can also specify a custom comparer for the elements:
- ```c#
- // Using StringComparison for string collections
- [OrderedEquality(StringComparison.OrdinalIgnoreCase)]
- public string[] Tags { get; set; }
- // Using a custom comparer type
- [OrderedEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
- public string[] Names { get; set; }
- // Using a custom IEqualityComparer<T> with a Default static member
- [OrderedEquality(typeof(MyCustomComparer))]
- public string[] Values { get; set; }
- ```
- ### UnorderedEquality
- ```c#
- [UnorderedEquality]
- public string[] Fruits { get; set; } // Does not care about the order of the fruits!
- [UnorderedEquality]
- public IDictionary<string, object> Properties { get; set; } // Works with dictionaries too!
- ```
- This equality comparer will compare properties as an unordered sequence instead of a reference. This works just like ```Enumerable.SequenceEqual```, but it does not care about the order as long as the all values (including the repetitions) are present.
- As with OrderedEquality, bear in mind that the property (or key and values if using a dictionary) has to implement IEnumerable<T> and the that the items themselves implement equality (you can use Generator.Equals in the items too!).
- You can also specify a custom comparer for the elements:
- ```c#
- // Using StringComparison for string collections
- [UnorderedEquality(StringComparison.OrdinalIgnoreCase)]
- public List<string> Tags { get; set; }
- // Using a custom comparer type
- [UnorderedEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
- public List<string> Names { get; set; }
- ```
- ### SetEquality
- ```c#
- [SetEquality]
- public HashSet<string> Fruits { get; set; } // Fruits can be in any order and duplicates are ignored
- ```
- This equality comparer will do a set comparison, using ```SetEquals``` whenever the underlying collection implements `ISet<T>`, otherwise falling back to manually comparing both collections, which can be expensive for large collections.
- You can also specify a custom comparer for the elements:
- ```c#
- // Using StringComparison for string collections
- [SetEquality(StringComparison.OrdinalIgnoreCase)]
- public HashSet<string> Tags { get; set; }
- // Using a custom comparer type
- [SetEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
- public HashSet<string> Names { get; set; }
- ```
- Hashing always returns 0 for this type of equality.
- ### ReferenceEquality
- ```c#
- [ReferenceEquality]
- public string Name { get; set; } // Will only return true if strings are the same reference (eg. when used with string.Intern)
- ```
- This will ignore whatever equality is implemented for a particular object and compare references instead.
- ### StringEquality
- ```c#
- [StringEquality(StringComparison.CurrentCulture | CurrentCultureIgnoreCase | InvariantCulture | InvariantCultureIgnoreCase | Ordinal | OrdinalIgnoreCase)]
- public string Title { get; set; } // Will use the StringComparison set in constructor when comparing strings
- ```
- ### PrecisionEquality
- ```c#
- [PrecisionEquality(0.001)]
- public double Temperature { get; set; } // Equal if Math.Abs(a - b) < 0.001
- [PrecisionEquality(5)]
- public int Score { get; set; } // Equal if Math.Abs(a - b) < 5
- [PrecisionEquality(0.001)]
- public double? NullableValue { get; set; } // Handles nulls: both null = equal, one null = not equal
- ```
- This equality comparer uses a tolerance (epsilon) to compare numeric values. Two values are considered equal when their absolute difference is less than the specified precision. This is excluded from `GetHashCode` since there is no stable bucketing under tolerance.
- Supported types: `float`, `double`, `decimal`, `int`, `long`, `short`, `sbyte`, and their nullable variants.
- ### CustomEquality
- ```c#
- class LengthEqualityComparer : IEqualityComparer<string>
- {
- public static readonly LengthEqualityComparer Default = new();
- public bool Equals(string? x, string? y) => x?.Length == y?.Length;
- public int GetHashCode(string obj) => obj.Length.GetHashCode();
- }
- class NameEqualityComparer
- {
- public static readonly IEqualityComparer<string> Default = new SomeCustomComparer();
- }
- [CustomEquality(typeof(LengthEqualityComparer))]
- public string Name1 { get; set; } // Will use LengthEqualityComparer to compare the values of Name1.
- [CustomEquality(typeof(NameEqualityComparer))]
- public string Name2 { get; set; } // Will use NameEqualityComparer.Default to compare values of Name2.
- [CustomEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
- public string Name2 { get; set; } // Will use StringComparer.OrdinalIgnoreCase to compare values of Name2.
- ```
- This attribute allows you to specify a custom comparer for a particular property. For it to work, the type passed as an
- argument to CustomEqualityAttribute should fulfill AT LEAST one of the following:
- * Have a static field/property named Default returning a valid IEqualityComparer<T> instance for the target type;
- * Have a static field/property with the same name passed to the CustomComparerAttribute returning a valid IEqualityComparer<T> instance for the target type;
- * Implement IEqualityComparer<T> and expose a parameterless constructor.
- ## Advanced Options
- ### Explicit Mode
- The generator allows you to explicitly specify which properties are used to generate the `IEquatable`.
- To do this, set the `Explicit` property of `EquatableAttribute` to `true` and specify the required properties using `DefaultEqualityAttribute` or other attributes.
- ```cs
- using Generator.Equals;
- [Equatable(Explicit = true)]
- partial class MyClass
- {
- // Only this property will be used for equality!
- [DefaultEquality]
- public string Name { get; set; } = "Konstantin";
- public string Description { get; set; } = "";
- }
- ```
- ### Ignore Inherited Members
- By default (`IgnoreInheritedMembers = false`), the generated code handles inherited members as follows:
- - If an ancestor owns equality — it has `[Equatable]`/a generated comparer, or hand-rolls a complete contract (a `GetHashCode()` override plus value equality via `IEquatable<T>` **or** an `Equals(object)` override) — the generated code calls `base.Equals()`/`base.GetHashCode()` to delegate to it. A public `IEquatable<T>` is preferred (delegation binds directly to it); `Equals(object)` is the fallback. Any plain classes *between* the decorated class and that ancestor (no `[Equatable]`, no equality of their own) have their public properties compared explicitly, since the ancestor knows nothing about them
- - A record base always owns its equality (compiler-synthesized or hand-written), so a derived record always delegates to it and never re-compares its members
- - Otherwise, all inherited properties from the entire chain are compared explicitly. A base that provides only one half — an `Equals`/`IEquatable` without `GetHashCode`, or vice versa — is treated this way too: delegating half a contract would break the `Equals`/`GetHashCode` invariant, so its public properties are compared instead
- `EqualityComparer.Inequalities` follows the same rules. When the base is delegated to via a generated comparer, its inequalities are reported member by member; when it is reached only through `base.Equals()` (a hand-written contract, or a record base without `[Equatable]`), the base portion is reported as a single whole-object inequality with an empty path. Likewise, when the generated `Equals` enforces a type-identity guard itself (`GetType()` for classes, `EqualityContract` for records), a mismatch is reported as a single whole-object inequality.
- Set `IgnoreInheritedMembers = true` to skip calling `base.Equals()` and ignore all inherited properties.
- This is useful when you want to completely redefine equality for a derived class without considering
- the base class's properties.
- ```cs
- using Generator.Equals;
- [Equatable]
- partial class Person
- {
- public string Name { get; set; }
- }
- [Equatable(IgnoreInheritedMembers = true)]
- partial class Doctor : Person
- {
- // Will NOT call base.Equals(), so Person.Name is not compared.
- // Only Id and Specialization are used for equality.
- public string Id { get; set; }
- public string Specialization { get; set; }
- }
- ```
- ### Equality Operators
- For classes, the generator emits `==` and `!=` alongside `Equals`, so both perform structural comparison.
- Set `GenerateClassEqualityOperators = false` to leave the operators out — `==` then falls back to C#'s
- default reference comparison, and you are free to declare the operators yourself.
- ```cs
- using Generator.Equals;
- [Equatable(GenerateClassEqualityOperators = false)]
- partial class Person
- {
- public string Name { get; set; }
- }
- var a = new Person { Name = "Ada" };
- var b = new Person { Name = "Ada" };
- a.Equals(b); // true - structural, as always
- a == b; // false - reference comparison
- ```
- Two limitations are worth knowing about, and the analyzer reports both:
- **The option only applies to classes (GE011).** Records always get compiler-generated operators, which the
- generator cannot suppress. Structs always get generated operators too, for a different reason: C# predefines
- `==` for reference types but not for user-defined struct types, so a struct only has `==` if something
- declares it. Dropping the generated operators would make every `==` and `!=` on the type a `CS0019` compile
- error — a class degrades to reference comparison, a struct has nothing to degrade to.
- **Opting out has to cover the whole inheritance chain (GE012).** C# operator overload resolution considers
- operators declared on base types, so a derived class that opts out still picks up its base's operators:
- ```cs
- [Equatable]
- partial class Person { public int Age { get; set; } }
- // GE012: the opt-out has no effect, Person's operators still apply to Manager operands
- [Equatable(GenerateClassEqualityOperators = false)]
- partial class Manager : Person { public string Department { get; set; } }
- ```
- Apply `GenerateClassEqualityOperators = false` to every `[Equatable]` class in the chain to get
- reference comparison throughout — one ancestor left at the default is enough to bring the operators
- back for every type below it.
- ## Inequalities
- Every `[Equatable]` type gets a generated `EqualityComparer` with an `Inequalities()` method that returns exactly which members differ between two instances — with full member paths, including nested objects, collection indices, and dictionary keys.
- ```c#
- [Equatable]
- partial record Customer
- {
- public required string Name { get; init; }
- [UnorderedEquality] public required ImmutableDictionary<string, Address> Addresses { get; init; }
- }
- [Equatable]
- partial record Address
- {
- public required string Street { get; init; }
- public required string City { get; init; }
- }
- ```
- ```c#
- var original = new Customer
- {
- Name = "John Doe",
- Addresses = ImmutableDictionary<string, Address>.Empty
- .Add("home", new Address { Street = "123 Main St", City = "Seattle" })
- };
- var modified = original with
- {
- Name = "Johnny Doe",
- Addresses = original.Addresses.SetItem("home",
- original.Addresses["home"] with { Street = "121 Main St" })
- };
- foreach (var diff in Customer.EqualityComparer.Default.Inequalities(original, modified))
- Console.WriteLine(diff);
- ```
- Output:
- ```
- Name: John Doe → Johnny Doe
- Addresses["home"].Street: 123 Main St → 121 Main St
- ```
- ### How it works
- `Inequalities()` returns `IEnumerable<Inequality>`, where each `Inequality` has:
- - **`Path`** — a `MemberPath` describing which member differs (e.g., `Addresses["home"].Street`)
- - **`Left`** — the value from the first object
- - **`Right`** — the value from the second object
- Paths are composed of segments:
- | Segment | Example | Meaning |
- |---------|---------|---------|
- | `Property` | `Name` | A property differs |
- | `Field` | `_count` | A field differs |
- | `Index` | `[0]` | An ordered collection element at index |
- | `Key` | `["home"]` | A dictionary entry by key |
- | `Added` | `[+]` | An element present only in the right collection |
- | `Removed` | `[-]` | An element present only in the left collection |
- For `[UnorderedEquality]` and `[SetEquality]` members, elements are matched using the member's configured element comparer (so `"FOO"` and `"foo"` under `StringComparison.OrdinalIgnoreCase` are not reported as a change). `[UnorderedEquality]` also respects multiplicity: `[1, 1, 2]` versus `[1, 2, 2]` reports one `1` removed and one `2` added. A `null` collection compared with an empty one is reported as a single difference on the member itself.
- ### Drill-down
- When an `[OrderedEquality]` collection element or dictionary value is itself an `[Equatable]` type, `Inequalities()` automatically drills down into its properties instead of reporting the entire object as changed. In the example above, the address change is reported as `Addresses["home"].Street` rather than the whole `Address` object. `[UnorderedEquality]` and `[SetEquality]` members report added/removed elements instead (see above), and a collection member without one of those attributes is reported as a single whole-member change.
- ### Base path
- You can pass a base path to prefix all reported paths — useful when composing inequalities from parent contexts:
- ```c#
- var diffs = Address.EqualityComparer.Default.Inequalities(
- addressA, addressB, new MemberPath(new[] { MemberPathSegment.Property("Home") }));
- // Reports: Home.Street, Home.City, etc.
- ```
- ## Migrating from version 4
- ### Fields are opt-in again (breaking change)
- **Version 5 reinstates the original rule that fields are excluded from equality unless explicitly
- annotated.** Properties are still compared by default; a field participates only when it carries
- `[DefaultEquality]` (or another equality attribute such as `[OrderedEquality]`).
- This corrects a regression: from **3.2.0 through 4.x**, fields were compared by default — the opposite
- of the intended and documented behavior. That change was accidental (a refactor dropped the field
- guard) and was never covered by a test, so it went unnoticed. Version 5 restores the intended
- behavior and marks it as breaking so the change is explicit.
- **What this means for you:** if you rely on a field being compared, annotate it. Nothing changes for
- properties.
- ```csharp
- [Equatable]
- public partial class User
- {
- public string Name { get; set; } // compared (property, default)
- private int _version; // v3.2–v4: compared | v5: NOT compared
- [DefaultEquality] private int _revision; // compared in all versions
- }
- ```
- > If you were on 3.1.x or earlier, no action is needed — v5 matches that behavior.
- ## Migrating from version 3
- ### Inherited Equality Attributes
- Version 4 introduces support for inherited equality attributes on overridden properties, making repeating attributes
- unnecessary. When a child class overrides a virtual property from a parent class, it now automatically inherits the
- equality attribute (e.g., `[OrderedEquality]`) from the parent. You no longer need to redeclare attributes on overriding
- properties.
- ```c#
- [Equatable]
- public partial class Parent
- {
- [OrderedEquality]
- public virtual int[] Values { get; set; }
- }
- [Equatable]
- public partial class Child : Parent
- {
- // Automatically inherits [OrderedEquality] from Parent
- public override int[] Values { get; set; }
- }
- ```
- ### Improved Inheritance Chain Detection
- The generator walks the **entire** inheritance chain and calls `base.Equals()`/`base.GetHashCode()` when an
- ancestor owns equality:
- 1. **Any ancestor** has the `[Equatable]` attribute (or a generated `EqualityComparer`, incl. cross-assembly), OR
- 2. **Any ancestor** hand-rolls a complete contract on that type — a `GetHashCode()` override plus value equality
- via a public `IEquatable<T>` (preferred) or an `Equals(object)` override (fallback) — so the base's
- hand-written semantics (which the generator cannot see into) are honored rather than re-derived from its
- public properties. A base providing only one half (equality without `GetHashCode`, or vice versa) is a
- `CS0659`/`CS0661`-style bug and is *not* delegated to; its public properties are compared instead so the
- generated pair stays self-consistent.
- This fixes scenarios where equality was incorrectly skipped in multi-level inheritance:
- ```c#
- [Equatable]
- public partial class GrandParent
- {
- public string Name { get; set; }
- }
- // No [Equatable] - inherits GrandParent's Equals
- public class Parent : GrandParent
- {
- public int Age { get; set; }
- }
- [Equatable]
- public partial class Child : Parent
- {
- public string School { get; set; }
- }
- ```
- **Before (v3):** `Child.Equals()` did NOT call `base.Equals()` because `Parent` lacks `[Equatable]`.
- Only `School` was compared, ignoring `Name`.
- **After (v4):** `Child.Equals()` calls `base.Equals()` because `GrandParent` has `[Equatable]`.
- Both `School` and `Name` are compared correctly.
- ### Ignore Inherited Members
- The `IgnoreInheritedMembers` property controls how inherited members are handled:
- | IgnoreInheritedMembers | Any Ancestor has [Equatable] | Behavior |
- |------------------------|------------------------------|----------|
- | `true` | N/A | Compare only declared members, type check, no `base.Equals()` |
- | `false` | Yes | Call `base.Equals()`, let ancestor handle its members |
- | `false` | No | Type check + compare ALL inherited properties from entire chain |
- ```c#
- [Equatable(IgnoreInheritedMembers = true)]
- public partial class Child : Parent
- {
- // Will NOT call base.Equals() even if Parent has [Equatable]
- // Only properties defined in Child are compared
- public string School { get; set; }
- }
- ```
- ## Migrating from version 2
- Migrating to version 3 is very straightforward.
- 1. Ensure projects are targeting C# 9.0 or latter using the MSBuild property `LangVersion`.
- 2. Be aware that `IEquatable<T>` for classes is now implemented explicitly in order to support deep equality. As a result, the method `Equals(T)` method is no longer marked as public. Most code should still work, requiring only to be recompiled as the ABI has changed.
- If you have an existing project using `Generator.Equals` and don't need any of the new features, you can still use version 2.x. The differences are minimal between both major versions.
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.