Search code examples
c#.netf#comparisonequality

How to do reference comparison in .NET?


In Equality and Comparison Constraints in F#, it said that:

Note there is no such thing as “reference comparison” (the object pointers used by .NET move around, so the ordering would change). You might implement that by using a unique tag and custom comparison.

How can I use an unique tag for comparison in F# and C#?


Solution

  • How to do reference comparison in .NET? How can I use an unique tag for comparison in F# and C#?

    Note that in this context, the word "comparison" is being used as distinct from "equality". It describes an ordering as opposed to just identity (which is supported). .And just as the referenced article says, if you want an ordering, you have to impose it yourself. The compiler can't infer one for you, nor can there be a default "reference comparison" as there is a default "reference equality".

    You can apply the StructuralComparison attribute to require that a type does in fact implement a comparison (similar to : comparison generic constraint), which allows ordering operations to occur. This gives you compile-time assurance from the compiler that your type meets the requirement that the inferred type implements a comparison.

    So, how do you do "reference comparison"? You don't! It wouldn't make sense to, just as the article says. You need to use a type that already has a comparison implemented, or e.g. implement IComparable<T> for your type, so that it meets the comparison constraint.

    If you need more help than that, you'll need to be more specific. Post a question that includes a good Minimal, Complete, and Verifiable code example showing what specific difficulty you are running into, trying to apply the advice in the referenced article to your own code, with a precise explanation of what you've tried, and what you're still having difficulty getting to work.