5

In F#:

[0] = [0] = true

In C# or .NET BCL in general:

StructuralComparisons.Equals(new int[] { 0 }, new int[] { 0 }) == false

Why?


Postscript:

The reason I thought I had the "right" Equals was because this turned out to be true:

var a = new { X = 3, Y = new { Z = -1 } };
var b = new { X = 3, Y = new { Z = -1 } };

StructuralComparisons.Equals(a, b) == true;
Bent Rasmussen
  • 5,538
  • 9
  • 44
  • 63
  • 1
    `new int[] { 0 }.SequenceEqual(new int[] { 0 }) == true;` – Dmitry Bychenko Aug 19 '15 at 12:32
  • Yes, but I want to have a general structural equality across object graphs - but just arrays as shown here. The reason I picked arrays was because they didn't equal. – Bent Rasmussen Aug 19 '15 at 12:32
  • Here is blog post from Don Syme on Equality and Comparison in F#: http://blogs.msdn.com/b/dsyme/archive/2009/11/08/equality-and-comparison-constraints-in-f-1-9-7.aspx – Petr Aug 19 '15 at 12:34
  • @Petr, thanks but I have/had no issues with F# ;-) ... but I just misread the API. I guess a method like StructuralComparisons.StructuralEquals would have saved me the embarassment. :-) – Bent Rasmussen Aug 19 '15 at 12:46
  • 2
    Just by the way, `[0]` is not an array in F#. – nphx Aug 19 '15 at 16:05

1 Answers1

8

That's because you're going down to object.Equals(objA, objB) which won't be able to handle that kind of comparison.

Instead do this:

StructuralComparisons.StructuralEqualityComparer.Equals(..., ...)
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • 2
    Don't be. The fact that they've embedded those helper methods down into the base of `object` has caused lots of bugs in lots of code, they're available through intellisense but is sometimes hard to differentiate from the ones you actually want. – Lasse V. Karlsen Aug 19 '15 at 12:35
  • Also, for the comment about why 0 == 0 according to object.Equals, this is explained in the [documentation](https://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx) which says that for reference types a reference comparison is made, but for value types, a value comparison is made. – Lasse V. Karlsen Aug 19 '15 at 12:36
  • I understand the reasoning behind primitive types but I was just confused by the counter-intuitiveness of StructuralComparisons.Equals actually being reference equality. But I should have looked closer. Sometimes it would be nice with member hiding. :P – Bent Rasmussen Aug 19 '15 at 12:37