4

I have a simple F# type as follows:

(* Num.fsi *)
namespace FsLib

module Num =
  [<NoEquality>]
  type t

  val of_int : int -> t
  val to_int : t -> int

Implementation is trivial as you might imagine, it's just a single-case discriminated union with an underlying int. Now in a C# project in the same solution I have the following code:

// CsTool.cs
using System;
using FsLib;

namespace CsTool {
  class MainClass {
    public static void Main(string[] args) {
      Num.t n1 = Num.of_int(1);
      Num.t n2 = Num.of_int(1);

      Console.WriteLine(n1.Equals(n2));
    }
  }
}

The problem is, this is printing False instead of failing to compile or throwing a runtime error. Any idea why this C# calling code is ignoring the [<NoEquality>] attribute?

By the way I am running this in Xamarin Studio Community on Mac, version 6.1.2, targeting .NET Framework version 4.5.1.

2
  • 4
    Well where in the C# language specification do you see anything suggesting the compiler should do anything with NoEqualityAttribute? Basically, that's not a cross-language-implemented attribute. You could potentially write a Roslyn analyzer to catch calls like that though.
    – Jon Skeet
    Mar 7, 2017 at 19:01
  • @JonSkeet ah, good to know. Thanks.
    – Yawar
    Mar 7, 2017 at 19:03

1 Answer 1

6

In general, the C# language will not handle many F# specific features. Most F# types, when used from F#, have different functionality. For example, F# types are (by default) unable to be set to null, but in C#, you can declare and set them to null because the C# language doesn't understand any of the F# specific constructs. As you've discovered, equality and comparison guarantees, nullable guarantees and features, and more are all ignored by C# (and other CLR languages).

In practice, this is rarely a problem, as most people tend to keep the F# types within their F# code base, and pull in types from the BCL or C# projects and convert them to F# types (to add the safety guarantees) "at the API boundaries".

4
  • OK, then another solution might be to override Object#Equals and throw an exception from there, I suppose.
    – Yawar
    Mar 7, 2017 at 20:56
  • 3
    @Yawar That's a very bad idea. The documentation for Object.Equals says that implementations must never throw exceptions, the result should be true or false. Mar 7, 2017 at 21:09
  • 3
    @TheInnerLight hmm, I was afraid of that. OK, then the only solution is to override it intelligently to a correct and meaningful equality test for my type.
    – Yawar
    Mar 7, 2017 at 21:31
  • 3
    @Yawar In general, yes, that's the best option - unless you want to keep reference equality. Mar 7, 2017 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.