Grzegorz Sławecki
Grzegorz Sławecki

Reputation: 1797

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?

Upvotes: 4

Views: 192

Answers (2)

Ringil
Ringil

Reputation: 6537

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.

Upvotes: 3

Mark Seemann
Mark Seemann

Reputation: 233150

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

> string 42;;
val it : string = "42"
> string ();;
val it : string = ""

Upvotes: 6

Related Questions