Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString throws NullReferenceException for unit value ()

Say we got a very simple function

let fn a = a.ToString()

It's type gets inferred as a -> string However, passing a unit value to the function results in a NullReferenceException.

In case of simple functions like above, this might be worked around easily, but I'm actually in a more complex scenario:

let eitherToHttp e = 
    match e with
    | Either.Ok v ->        OK (v.ToString()) 
    | Either.Bad reason ->  reasonToErrorCode reason

The type of this is Either<'a, RejectReason> -> WebPart (what WebPart and Either actually are is irrelevant here)

In a scenario where the type of e is Either<unit, RejectReason> the function throws exactly like in the simple scenario.

How can I overcome this in a nice way? Should the types be inferred as generic if in fact this does not work for ALL types?

like image 207
Grzegorz Sławecki Avatar asked Jan 04 '23 20:01

Grzegorz Sławecki


2 Answers

Use the built-in string function instead of calling ToString on the object:

> string 42;;
val it : string = "42"
> string ();;
val it : string = ""
like image 114
Mark Seemann Avatar answered Jan 12 '23 03:01

Mark Seemann


You can do something like this:

let fn a = match box a with
           | null -> ""
           | _ -> a.ToString()

This compiles down to just a null check on a before attempting to call ToString.

like image 22
Ringil Avatar answered Jan 12 '23 03:01

Ringil