2

If at least 1 struct field is of reference type, default Equals method implementation for this struct uses reflection to call Equals for each field.

Reflection at run-time is very heavy. Why not just autogenerate default Equals method for such structs while compiling to avoid run-time reflection using?

user1234567
  • 3,991
  • 3
  • 19
  • 25
  • Where have you seen that code? – Julian Aug 18 '19 at 11:55
  • @Julian, https://referencesource.microsoft.com/#mscorlib/system/valuetype.cs. (also corrected the question a little) – user1234567 Aug 18 '19 at 11:58
  • 1
    I see also indeed "If none of the fields of the current instance and obj are reference types, the Equals method performs a byte-by-byte comparison of the two objects in memory. Otherwise, it uses reflection to compare the corresponding fields of obj and this instance." From https://learn.microsoft.com/en-us/dotnet/api/system.valuetype.equals?view=netframework-4.8 – Julian Aug 18 '19 at 12:01
  • I think because the concrete type is not always known at compile time so it has to do this at runtime. – CodingYoshi Aug 18 '19 at 12:33
  • 1
    I believe the hope is that `Equals` will be overridden in those cases and thus it was likely deemed not to be a worth wild feature to implement. But really only the C# designers can definitively answer why they choose to implement something one way or the other. – juharr Aug 18 '19 at 12:36
  • You are stating: Reflection at run-time is very heavy. I believe you can leave the word "very"out and you really need to think if the overhead of reflection is an issue for you.. – Aldert Aug 18 '19 at 12:40
  • The duplicate was found by Googling for `Why default Equals method implementation for structs uses reflection?`. – mjwills Aug 18 '19 at 12:41
  • `Why not just autogenerate` I've found https://blogs.msdn.microsoft.com/ericgu/2004/01/12/minus-100-points/ a helpful article for thinking through why stuff isn't done. – mjwills Aug 18 '19 at 13:36

0 Answers0