Properly implement F # Unit in C #

This question does not concern C # / F # compatibility, as in this one .

I would like to know how to use void to create an F # Unit type .

Obviously, I will drop this result, and I will not expose this type to the outside world.

I wonder if an empty class can impersonate this role.

 internal class Unit { } 

For example, in the language-ext library, the author used struct .

Is there any benefit to this choice?

+7
c # functional-programming f # unit-type
source share
2 answers

I am not sure what the best way to determine Unit for use with C #. This may differ from how it is done in F # (because in F # the compiler hides the use in some way).

However, you can really find the F # Unit implementation in the main library:

Here are the key points to implement the F # Unit

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

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

+6
source share

System.ValueTuple (without a common argument) is a lot of units in C #. The source code is open.

+1
source share

All Articles