Discriminated unions and other primitive types in F# uses structural equality by default, and provides a generated override for the .Equals method. The F# equality operator apparently differs from the C# one in that it uses the .Equals method even for reference types, but when F# discriminated unions are used from C#, the default operator== for object is used, which checks for reference equality rather than structural equality.
Why does not F# generate a custom operator== for discriminated union types so that == gives the expected behaviour when used in other .NET languages?
Such behaviour is defined by the language you are using and not by the language of origin of the type you are using.
I'm not on the F# team, so I can only speculate, but here are a few potential reasons:
Equals
method. C# provides ways to test for two distinct kinds of equality - why should F# force them to behave in the same way when a might prefer to be able to use reference equality?If you want to force C# to use structural equality, it's easy to do it yourself:
type T = A | B of int with
static member op_Equality(t:T,t2:T) = t = t2
// or even static member (=)(t:T, t2:T) = t = t2
There's a development cost to any feature, so even if there were a clear benefit to automatically generating an op_Equality
, it might have been dropped in favor of higher priority features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With