1

I am using record from C# 9, for example

public record Receipt
{
    public string ClientName { get; init; } = "";

    public string ClientPhoneNumber { get; init; } = "";

    public List<OtherRecord> OtherInfo { get; init; } = new();
}

and would like a function to compare 2 instances of that type and return a list of all values that are not identical on both sides (for auditing purpose).

I suppose it would use reflection so it can support any record type, without hardcoding the properties names?

Bruno
  • 4,685
  • 7
  • 54
  • 105
  • records do that automatically - see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record#value-equality – pm100 Dec 12 '22 at 01:43
  • @pm100 yes but I want to know more than just if the 2 instances are equal – Bruno Dec 12 '22 at 01:49
  • 1
    i missed that, yes reflection is the way to go – pm100 Dec 12 '22 at 02:12
  • things will get nasty for non primitive fields (like OtherInfo in your example) – pm100 Dec 12 '22 at 02:19
  • @pm100 maybe...however all fields are either primitive or another record or a list of other records, and all records have only primitive fields or other records like that. So it's still a relatively simple model, it all eventually ends up to primitives. – Bruno Dec 12 '22 at 03:10
  • so you have to do recursize descent to compare, might be interesting to look at what c# generates fro simply comparing 2 records, does it do a deep compare? – pm100 Dec 12 '22 at 03:15
  • Just putting this out there, for something quick and dirty when debugging, you could use a JsonSerializer on both records, and just leverage your existing diff viewer. E.g. if you have some deep & complex object structure produced by 2 different methods, and you'd like to see how the outputs differ. – NPras Dec 12 '22 at 04:15

1 Answers1

1

https://github.com/GregFinzer/Compare-Net-Objects

I have found this to be excellent (I am in no way linked to the author or the project)

Dale Holborow
  • 560
  • 3
  • 19