how to easily exclude properties from record equality? #4257
Replies: 4 comments 2 replies
-
I believe, by design, the answer here is to implement |
Beta Was this translation helpful? Give feedback.
-
@theunrepentantgeek ,i'm also trying to do a source generator for my senarios, where simply a equal override seems not enough |
Beta Was this translation helpful? Give feedback.
-
I agree that it's one of the logical growth points for this feature. Reimplementing the whole equality is usually a big pain in the neck if all you need is to add a sequence-equal collection member or exclude a volatile member. An attribute that supplies a different equality comparer for a member would work well, but I would settle for a helper like |
Beta Was this translation helpful? Give feedback.
-
Like others suggested, the intended way to solve this is by manually implementing the Equals method. If writing the Equals manually is really too cumbersome in your case or sensitive to mistakes, you can also consider wrapping the member in a type that implements equality as always true. public readonly struct IgnoreEquals<T>(T value) {
public T Value { get; init; } = value;
public override bool Equals(object? obj) => true;
public override int GetHashCode() => 0;
public override string? ToString() => Value?.ToString();
} Then in your record types: record Foo {
private IgnoreEquals<int> _ignoreThisMemberInEquals = new(0);
} This way the compiler generated Equals will still work. |
Beta Was this translation helpful? Give feedback.
-
i have a record
where User is not a init property and i dont want it to be within equality consideration.
any easy way to make it happen?
Beta Was this translation helpful? Give feedback.
All reactions