简体   繁体   中英

Properly implement F# Unit in C#

This question is not about C#\/F# compatibility as in this one<\/a> .

internal class Unit
{
}

I'm not sure what is the best way to define Unit for usage from C#. It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way).

However, you can actually find the implementation of F# unit in the core library:

Here are the key points about the F# unit implementation

  • It implements GetHashCode and Equals in the same way to the Rx version
  • It is IComparable and all values of the unit type are equal
  • Most importantly, it has a private constructor and so you cannot create a new unit value. It also has no default instance (unlike the Rx unit) and so in F#, all unit values are actually represented as null . However, the language/compiler generally hide this fact.

So, it sounds like the only difference in F# is that it uses the null value. If you want to use unit explicitly, this might not be the best choice. However, if you have Unit.Default then you are ultimately defining a type with two possible values, because it can be either Unit.Default or null (and so it is not really a unit!)

System.ValueTuple (without generic argument) is very much unit in C#. The source code is open.

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