简体   繁体   中英

C# project not honouring F# type `[<NoEquality>]` attribute

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.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM