4

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.

MotKohn
  • 3,485
  • 1
  • 24
  • 41
  • 2
    You seem to know that you [can make your own equality logic](https://stackoverflow.com/questions/64326511/custom-equality-check-for-c-sharp-9-records), what brought you on to using attributes? Total shot in the dark? – gunr2171 Jan 11 '23 at 17:17
  • @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. – MotKohn Jan 11 '23 at 17:35

1 Answers1

1

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

Guru Stron
  • 102,774
  • 10
  • 95
  • 132