How do you return a null Tuple from f# to c#?

Viewed 118

I have this type-correct C# function:

static System.Tuple<int,int> f(int n) { 
  switch (n) { 
    case 0: return null;
    default: return System.Tuple.Create(n,n+1);
  }
}

I try to re-implement it in F#:

let f = function 
| 0 -> null 
| n -> System.Tuple.Create(n, n+1)

Type-checker disagrees, though:

error FS0001: The type '('a * 'b)' does not have 'null' as a proper value.

How do I re-implement the original C# function f in F#?

Note that while this looks like the question “how do I return null in F#” (answer: don’t, use Option) we are asking the slightly different “how do we return null from F# for C# consumers” (can’t use Option, helpful answer below).

1 Answers

If you need it to interop with C#, you can use Unchecked.Defaultof like so:

let f = function
    | 0 -> Unchecked.Defaultof<_>
    | n -> (n, n + 1)

However, using null values is strongly discouraged in F#, and if interoperability is not your main concern, using an option is much more natural:

let f = function
    | 0 -> None
    | n -> Some (n, n + 1)
Related