Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C# attribute on a record field to exclude a field from comparison?

Tags:

c#

c#-9.0

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.

like image 220
MotKohn Avatar asked Jan 30 '26 07:01

MotKohn


1 Answers

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.

like image 105
Guru Stron Avatar answered Jan 31 '26 21:01

Guru Stron