15

I am getting data with an updated timestamp that I would like to ignore for example:

public record Person
{
    public string LastName,
    public string FirstName,
    public string MiddleName,
    [isThereAnAttributeThatICanPutHere]
    public DateTime UpdatedAt
}

C# records auto generates code that compares records by value, and I would like to take advantage of that feature but need to exclude one field. I know that I can provide my own GetHashCode but that would defeat the purpose of trying to stay simple. I also know that I can compare with the following:

person1 with {UpdateAt = null} == person2 with {UpdateAt = null} // this will need UpdatedAt to be nullable

but that looks like needless allocations.

4
  • 2
    You seem to know that you can make your own equality logic, what brought you on to using attributes? Total shot in the dark? Commented Jan 11, 2023 at 17:17
  • 2
    @gunr2171 Too many fields to compare in my case, I'm looking for a shortcut - a way that it is all generated on its own. Commented Jan 11, 2023 at 17:35
  • 2
    Not an answer to the question, but for the benefit of anyone else who has the same question, I find that a simple, low-overheard approach this this is to compare using nondestructive mutation to equalize the properties that we want ignored. e.g.: var result = instance1 with { UpdatedAt = DateTime.MinValue } == instance2 with { UpdatedAt = DateTime.MinValue }; An extension method could be used to make this more succinct. Commented Sep 27, 2023 at 12:19
  • With too many fields you may want to extract ignored fields into another record. This new record can work as a wrapper to hold ignored fields and original record (without ignored fields) as a new member. Compare only that new member. Commented Oct 15, 2024 at 10:21

1 Answer 1

8

No, at the moment there is nothing built-in, so unless you are willing to write your own custom implementation (potentially using source generators), you are limited to manually overriding Equals (and GetHashCode, just in case). Something similar was discussed for PrintMembers in this issue, and it seems that the attribute approach is not considered by the .NET team.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.