Why do I need to use the unit type in F# if it supports the void type?

Viewed 1528

I read this MSDN article:

Unit Type (F#)

...The unit type is a type that indicates the absence of a specific value; the unit type has only a single value, which acts as a placeholder when no other value exists or is needed ... The unit type resembles the void type in languages such as C# and C++...

So... Alright, I understand, that the unit type is such a type, which has only a single value (). But I have some questions:

  1. Why is it needed?
  2. When is it needed?

I don't understand why not to use the void type in F#, like C# and C++ use.

If I look at the following table:

Primitive Types (F#)

Type   .NET Type    Description  
void   Void         Indicates no type or value.

I see that F# does have a void type. So I don't understand why the unit type needed; it looks like it is very similar to void.

I suppose that it relates to the functional language paradigm and that's why it's needed, so please... explain more about this to me.

4 Answers

This article explains some limitations of void and why you even might want to have Unit in C#: https://chtenb.dev/?page=unit-cs

The bottom line is that you can't use void as a type parameter in generic types, like Task<void>. Using a unit type instead of void solves this problem.

This is the Unit implementation used in the article.

public struct Unit : IEquatable<Unit>
{
  public static readonly Unit unit;
  public override bool Equals(object obj) => obj is Unit;
  public override int GetHashCode() => 0;
  public static bool operator ==(Unit left, Unit right) => left.Equals(right);
  public static bool operator !=(Unit left, Unit right) => !(left == right);
  public bool Equals(Unit other) => true;
  public override string ToString() => "()";
}
Related