Skip to content
Back to search

Generator.Equals

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/diegofrata--generator-equals/badge.svg)](/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)

  1. [![Nuget](https://img.shields.io/nuget/v/Generator.Equals)](https://www.nuget.org/packages/Generator.Equals/)
  2. # Generator.Equals
  3. A C# source generator that automatically implements `IEquatable<T>`, `Equals`, and `GetHashCode` — using just attributes.
  4. 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.
  5. ### Why use Generator.Equals?
  6. - **Zero boilerplate** — Mark your type with `[Equatable]` and the generator does the rest. No hand-written `Equals`, `GetHashCode`, or `==`/`!=` operators.
  7. - **Collection-aware** — Compare arrays, lists, dictionaries, and sets by value out of the box with `[OrderedEquality]`, `[UnorderedEquality]`, and `[SetEquality]`.
  8. - **Highly customizable** — Use `[CustomEquality]`, `[StringEquality]`, `[PrecisionEquality]`, `[ReferenceEquality]`, or `[IgnoreEquality]` to control comparison per-property.
  9. - **Works everywhere** — Supports classes, structs, records, and record structs.
  10. - **Inheritance-friendly** — Correctly chains `base.Equals()` across deep inheritance hierarchies and inherits equality attributes from overridden properties.
  11. - **Structured diffs** — Call `Inequalities()` to get exactly which members differ between two instances, with full paths into nested objects, collections, and dictionaries.
  12. - **Compile-time only** — No reflection or IL injection. The generator emits plain C# source code that you can inspect and debug.
  13. ----------------
  14. ## Requirements
  15. In order to use this library, you must:
  16. * Use a target framework that supports .NET Standard >= 2.0
  17. * Set your project's C# ```LangVersion``` property to 9.0 or higher.
  18. ## Installation
  19. Simply add the package `Generator.Equals` to your project. Keep reading to learn how to add the attributes to your types.
  20. ## Usage
  21. 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.
  22. ```c#
  23. using Generator.Equals;
  24. [Equatable]
  25. partial record MyRecord(
  26. [property: OrderedEquality] string[] Fruits
  27. );
  28. class Program
  29. {
  30. static void Main(string[] args)
  31. {
  32. var record1 = new MyRecord(new[] {"banana", "apple"});
  33. var record2 = new MyRecord(new[] {"banana", "apple"});
  34. var record3 = new MyRecord(new[] {"banana", "cherry"});
  35. // Use the generated == operator
  36. Console.WriteLine(record1 == record2); // True
  37. // Use the generated comparer directly
  38. Console.WriteLine(MyRecord.EqualityComparer.Default.Equals(record1, record3)); // False
  39. // List exactly which members differ between two instances
  40. foreach (var diff in MyRecord.EqualityComparer.Default.Inequalities(record1, record3))
  41. Console.WriteLine(diff);
  42. // Output:
  43. // Fruits[1]: apple → cherry
  44. }
  45. }
  46. ```
  47. Need more than records? Generator.Equals supports properties (and fields) also across classes, structs and record structs.
  48. ```c#
  49. using Generator.Equals;
  50. [Equatable]
  51. partial class MyClass
  52. {
  53. [DefaultEquality]
  54. private int _secretNumber = 42;
  55. [OrderedEquality]
  56. public string[] Fruits { get; set; }
  57. }
  58. [Equatable]
  59. partial struct MyStruct
  60. {
  61. [OrderedEquality]
  62. public string[] Fruits { get; set; }
  63. }
  64. [Equatable]
  65. partial record struct MyRecordStruct(
  66. [property: OrderedEquality] string[] Fruits
  67. );
  68. ```
  69. ## Supported Comparers
  70. 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!
  71. ### Default
  72. This is the comparer that's used when a property has no attributes indicating otherwise. The generated code will use
  73. ```EqualityComparer<T>.Default``` for both equals and hashing operation.
  74. > _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)._
  75. ### IgnoreEquality
  76. ```c#
  77. [IgnoreEquality]
  78. public string Name { get; set; }
  79. ```
  80. As the name implies, the property is ignored during Equals and GetHashCode calls!
  81. ### OrderedEquality
  82. ```c#
  83. [OrderedEquality]
  84. public string[] Fruits { get; set; } // Fruits have to be in the same order for the array to be considered equal.
  85. ```
  86. 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.
  87. 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!).
  88. You can also specify a custom comparer for the elements:
  89. ```c#
  90. // Using StringComparison for string collections
  91. [OrderedEquality(StringComparison.OrdinalIgnoreCase)]
  92. public string[] Tags { get; set; }
  93. // Using a custom comparer type
  94. [OrderedEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
  95. public string[] Names { get; set; }
  96. // Using a custom IEqualityComparer<T> with a Default static member
  97. [OrderedEquality(typeof(MyCustomComparer))]
  98. public string[] Values { get; set; }
  99. ```
  100. ### UnorderedEquality
  101. ```c#
  102. [UnorderedEquality]
  103. public string[] Fruits { get; set; } // Does not care about the order of the fruits!
  104. [UnorderedEquality]
  105. public IDictionary<string, object> Properties { get; set; } // Works with dictionaries too!
  106. ```
  107. 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.
  108. 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!).
  109. You can also specify a custom comparer for the elements:
  110. ```c#
  111. // Using StringComparison for string collections
  112. [UnorderedEquality(StringComparison.OrdinalIgnoreCase)]
  113. public List<string> Tags { get; set; }
  114. // Using a custom comparer type
  115. [UnorderedEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
  116. public List<string> Names { get; set; }
  117. ```
  118. ### SetEquality
  119. ```c#
  120. [SetEquality]
  121. public HashSet<string> Fruits { get; set; } // Fruits can be in any order and duplicates are ignored
  122. ```
  123. 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.
  124. You can also specify a custom comparer for the elements:
  125. ```c#
  126. // Using StringComparison for string collections
  127. [SetEquality(StringComparison.OrdinalIgnoreCase)]
  128. public HashSet<string> Tags { get; set; }
  129. // Using a custom comparer type
  130. [SetEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
  131. public HashSet<string> Names { get; set; }
  132. ```
  133. Hashing always returns 0 for this type of equality.
  134. ### ReferenceEquality
  135. ```c#
  136. [ReferenceEquality]
  137. public string Name { get; set; } // Will only return true if strings are the same reference (eg. when used with string.Intern)
  138. ```
  139. This will ignore whatever equality is implemented for a particular object and compare references instead.
  140. ### StringEquality
  141. ```c#
  142. [StringEquality(StringComparison.CurrentCulture | CurrentCultureIgnoreCase | InvariantCulture | InvariantCultureIgnoreCase | Ordinal | OrdinalIgnoreCase)]
  143. public string Title { get; set; } // Will use the StringComparison set in constructor when comparing strings
  144. ```
  145. ### PrecisionEquality
  146. ```c#
  147. [PrecisionEquality(0.001)]
  148. public double Temperature { get; set; } // Equal if Math.Abs(a - b) < 0.001
  149. [PrecisionEquality(5)]
  150. public int Score { get; set; } // Equal if Math.Abs(a - b) < 5
  151. [PrecisionEquality(0.001)]
  152. public double? NullableValue { get; set; } // Handles nulls: both null = equal, one null = not equal
  153. ```
  154. 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.
  155. Supported types: `float`, `double`, `decimal`, `int`, `long`, `short`, `sbyte`, and their nullable variants.
  156. ### CustomEquality
  157. ```c#
  158. class LengthEqualityComparer : IEqualityComparer<string>
  159. {
  160. public static readonly LengthEqualityComparer Default = new();
  161. public bool Equals(string? x, string? y) => x?.Length == y?.Length;
  162. public int GetHashCode(string obj) => obj.Length.GetHashCode();
  163. }
  164. class NameEqualityComparer
  165. {
  166. public static readonly IEqualityComparer<string> Default = new SomeCustomComparer();
  167. }
  168. [CustomEquality(typeof(LengthEqualityComparer))]
  169. public string Name1 { get; set; } // Will use LengthEqualityComparer to compare the values of Name1.
  170. [CustomEquality(typeof(NameEqualityComparer))]
  171. public string Name2 { get; set; } // Will use NameEqualityComparer.Default to compare values of Name2.
  172. [CustomEquality(typeof(StringComparer), nameof(StringComparer.OrdinalIgnoreCase))]
  173. public string Name2 { get; set; } // Will use StringComparer.OrdinalIgnoreCase to compare values of Name2.
  174. ```
  175. This attribute allows you to specify a custom comparer for a particular property. For it to work, the type passed as an
  176. argument to CustomEqualityAttribute should fulfill AT LEAST one of the following:
  177. * Have a static field/property named Default returning a valid IEqualityComparer<T> instance for the target type;
  178. * Have a static field/property with the same name passed to the CustomComparerAttribute returning a valid IEqualityComparer<T> instance for the target type;
  179. * Implement IEqualityComparer<T> and expose a parameterless constructor.
  180. ## Advanced Options
  181. ### Explicit Mode
  182. The generator allows you to explicitly specify which properties are used to generate the `IEquatable`.
  183. To do this, set the `Explicit` property of `EquatableAttribute` to `true` and specify the required properties using `DefaultEqualityAttribute` or other attributes.
  184. ```cs
  185. using Generator.Equals;
  186. [Equatable(Explicit = true)]
  187. partial class MyClass
  188. {
  189. // Only this property will be used for equality!
  190. [DefaultEquality]
  191. public string Name { get; set; } = "Konstantin";
  192. public string Description { get; set; } = "";
  193. }
  194. ```
  195. ### Ignore Inherited Members
  196. By default (`IgnoreInheritedMembers = false`), the generated code handles inherited members as follows:
  197. - 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
  198. - 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
  199. - 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
  200. `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.
  201. Set `IgnoreInheritedMembers = true` to skip calling `base.Equals()` and ignore all inherited properties.
  202. This is useful when you want to completely redefine equality for a derived class without considering
  203. the base class's properties.
  204. ```cs
  205. using Generator.Equals;
  206. [Equatable]
  207. partial class Person
  208. {
  209. public string Name { get; set; }
  210. }
  211. [Equatable(IgnoreInheritedMembers = true)]
  212. partial class Doctor : Person
  213. {
  214. // Will NOT call base.Equals(), so Person.Name is not compared.
  215. // Only Id and Specialization are used for equality.
  216. public string Id { get; set; }
  217. public string Specialization { get; set; }
  218. }
  219. ```
  220. ### Equality Operators
  221. For classes, the generator emits `==` and `!=` alongside `Equals`, so both perform structural comparison.
  222. Set `GenerateClassEqualityOperators = false` to leave the operators out — `==` then falls back to C#'s
  223. default reference comparison, and you are free to declare the operators yourself.
  224. ```cs
  225. using Generator.Equals;
  226. [Equatable(GenerateClassEqualityOperators = false)]
  227. partial class Person
  228. {
  229. public string Name { get; set; }
  230. }
  231. var a = new Person { Name = "Ada" };
  232. var b = new Person { Name = "Ada" };
  233. a.Equals(b); // true - structural, as always
  234. a == b; // false - reference comparison
  235. ```
  236. Two limitations are worth knowing about, and the analyzer reports both:
  237. **The option only applies to classes (GE011).** Records always get compiler-generated operators, which the
  238. generator cannot suppress. Structs always get generated operators too, for a different reason: C# predefines
  239. `==` for reference types but not for user-defined struct types, so a struct only has `==` if something
  240. declares it. Dropping the generated operators would make every `==` and `!=` on the type a `CS0019` compile
  241. error — a class degrades to reference comparison, a struct has nothing to degrade to.
  242. **Opting out has to cover the whole inheritance chain (GE012).** C# operator overload resolution considers
  243. operators declared on base types, so a derived class that opts out still picks up its base's operators:
  244. ```cs
  245. [Equatable]
  246. partial class Person { public int Age { get; set; } }
  247. // GE012: the opt-out has no effect, Person's operators still apply to Manager operands
  248. [Equatable(GenerateClassEqualityOperators = false)]
  249. partial class Manager : Person { public string Department { get; set; } }
  250. ```
  251. Apply `GenerateClassEqualityOperators = false` to every `[Equatable]` class in the chain to get
  252. reference comparison throughout — one ancestor left at the default is enough to bring the operators
  253. back for every type below it.
  254. ## Inequalities
  255. 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.
  256. ```c#
  257. [Equatable]
  258. partial record Customer
  259. {
  260. public required string Name { get; init; }
  261. [UnorderedEquality] public required ImmutableDictionary<string, Address> Addresses { get; init; }
  262. }
  263. [Equatable]
  264. partial record Address
  265. {
  266. public required string Street { get; init; }
  267. public required string City { get; init; }
  268. }
  269. ```
  270. ```c#
  271. var original = new Customer
  272. {
  273. Name = "John Doe",
  274. Addresses = ImmutableDictionary<string, Address>.Empty
  275. .Add("home", new Address { Street = "123 Main St", City = "Seattle" })
  276. };
  277. var modified = original with
  278. {
  279. Name = "Johnny Doe",
  280. Addresses = original.Addresses.SetItem("home",
  281. original.Addresses["home"] with { Street = "121 Main St" })
  282. };
  283. foreach (var diff in Customer.EqualityComparer.Default.Inequalities(original, modified))
  284. Console.WriteLine(diff);
  285. ```
  286. Output:
  287. ```
  288. Name: John Doe → Johnny Doe
  289. Addresses["home"].Street: 123 Main St → 121 Main St
  290. ```
  291. ### How it works
  292. `Inequalities()` returns `IEnumerable<Inequality>`, where each `Inequality` has:
  293. - **`Path`** — a `MemberPath` describing which member differs (e.g., `Addresses["home"].Street`)
  294. - **`Left`** — the value from the first object
  295. - **`Right`** — the value from the second object
  296. Paths are composed of segments:
  297. | Segment | Example | Meaning |
  298. |---------|---------|---------|
  299. | `Property` | `Name` | A property differs |
  300. | `Field` | `_count` | A field differs |
  301. | `Index` | `[0]` | An ordered collection element at index |
  302. | `Key` | `["home"]` | A dictionary entry by key |
  303. | `Added` | `[+]` | An element present only in the right collection |
  304. | `Removed` | `[-]` | An element present only in the left collection |
  305. 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.
  306. ### Drill-down
  307. 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.
  308. ### Base path
  309. You can pass a base path to prefix all reported paths — useful when composing inequalities from parent contexts:
  310. ```c#
  311. var diffs = Address.EqualityComparer.Default.Inequalities(
  312. addressA, addressB, new MemberPath(new[] { MemberPathSegment.Property("Home") }));
  313. // Reports: Home.Street, Home.City, etc.
  314. ```
  315. ## Migrating from version 4
  316. ### Fields are opt-in again (breaking change)
  317. **Version 5 reinstates the original rule that fields are excluded from equality unless explicitly
  318. annotated.** Properties are still compared by default; a field participates only when it carries
  319. `[DefaultEquality]` (or another equality attribute such as `[OrderedEquality]`).
  320. This corrects a regression: from **3.2.0 through 4.x**, fields were compared by default — the opposite
  321. of the intended and documented behavior. That change was accidental (a refactor dropped the field
  322. guard) and was never covered by a test, so it went unnoticed. Version 5 restores the intended
  323. behavior and marks it as breaking so the change is explicit.
  324. **What this means for you:** if you rely on a field being compared, annotate it. Nothing changes for
  325. properties.
  326. ```csharp
  327. [Equatable]
  328. public partial class User
  329. {
  330. public string Name { get; set; } // compared (property, default)
  331. private int _version; // v3.2–v4: compared | v5: NOT compared
  332. [DefaultEquality] private int _revision; // compared in all versions
  333. }
  334. ```
  335. > If you were on 3.1.x or earlier, no action is needed — v5 matches that behavior.
  336. ## Migrating from version 3
  337. ### Inherited Equality Attributes
  338. Version 4 introduces support for inherited equality attributes on overridden properties, making repeating attributes
  339. unnecessary. When a child class overrides a virtual property from a parent class, it now automatically inherits the
  340. equality attribute (e.g., `[OrderedEquality]`) from the parent. You no longer need to redeclare attributes on overriding
  341. properties.
  342. ```c#
  343. [Equatable]
  344. public partial class Parent
  345. {
  346. [OrderedEquality]
  347. public virtual int[] Values { get; set; }
  348. }
  349. [Equatable]
  350. public partial class Child : Parent
  351. {
  352. // Automatically inherits [OrderedEquality] from Parent
  353. public override int[] Values { get; set; }
  354. }
  355. ```
  356. ### Improved Inheritance Chain Detection
  357. The generator walks the **entire** inheritance chain and calls `base.Equals()`/`base.GetHashCode()` when an
  358. ancestor owns equality:
  359. 1. **Any ancestor** has the `[Equatable]` attribute (or a generated `EqualityComparer`, incl. cross-assembly), OR
  360. 2. **Any ancestor** hand-rolls a complete contract on that type — a `GetHashCode()` override plus value equality
  361. via a public `IEquatable<T>` (preferred) or an `Equals(object)` override (fallback) — so the base's
  362. hand-written semantics (which the generator cannot see into) are honored rather than re-derived from its
  363. public properties. A base providing only one half (equality without `GetHashCode`, or vice versa) is a
  364. `CS0659`/`CS0661`-style bug and is *not* delegated to; its public properties are compared instead so the
  365. generated pair stays self-consistent.
  366. This fixes scenarios where equality was incorrectly skipped in multi-level inheritance:
  367. ```c#
  368. [Equatable]
  369. public partial class GrandParent
  370. {
  371. public string Name { get; set; }
  372. }
  373. // No [Equatable] - inherits GrandParent's Equals
  374. public class Parent : GrandParent
  375. {
  376. public int Age { get; set; }
  377. }
  378. [Equatable]
  379. public partial class Child : Parent
  380. {
  381. public string School { get; set; }
  382. }
  383. ```
  384. **Before (v3):** `Child.Equals()` did NOT call `base.Equals()` because `Parent` lacks `[Equatable]`.
  385. Only `School` was compared, ignoring `Name`.
  386. **After (v4):** `Child.Equals()` calls `base.Equals()` because `GrandParent` has `[Equatable]`.
  387. Both `School` and `Name` are compared correctly.
  388. ### Ignore Inherited Members
  389. The `IgnoreInheritedMembers` property controls how inherited members are handled:
  390. | IgnoreInheritedMembers | Any Ancestor has [Equatable] | Behavior |
  391. |------------------------|------------------------------|----------|
  392. | `true` | N/A | Compare only declared members, type check, no `base.Equals()` |
  393. | `false` | Yes | Call `base.Equals()`, let ancestor handle its members |
  394. | `false` | No | Type check + compare ALL inherited properties from entire chain |
  395. ```c#
  396. [Equatable(IgnoreInheritedMembers = true)]
  397. public partial class Child : Parent
  398. {
  399. // Will NOT call base.Equals() even if Parent has [Equatable]
  400. // Only properties defined in Child are compared
  401. public string School { get; set; }
  402. }
  403. ```
  404. ## Migrating from version 2
  405. Migrating to version 3 is very straightforward.
  406. 1. Ensure projects are targeting C# 9.0 or latter using the MSBuild property `LangVersion`.
  407. 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.
  408. 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 in

Free to use. If it’s helped, pass it on.