Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding ToString and `%A` specifier

If a override ToString in a type

type TestMe ()=
    override __.ToString() = null

and then I output it through the "%A" specifier

printfn "*%A*" (TestMe())

why does it throw a System.NullReferenceException?

I would have expected it to behave like

printfn "*%A*" null

which simply prints <null> without any exceptions.


1 Answers

This issue got fixed in F# 4.1, which now explicitly handles the case where ToString() returns null. Before that fix, the null would travel up the stack and eventually be dereferenced.

Upgrading your FSharp.Core version will fix the issue for you.

Having said that, I'd like to point out that returning null from ToString is a generally a big no-no. Even MSDN docs have a specific warning about it.

like image 191
Fyodor Soikin Avatar answered Jan 23 '26 21:01

Fyodor Soikin