Search code examples
f#nulloption-type

Forcing a field of an F# type to be null


I understand well the benefit of option, but in this case, I want to avoid using option for performance reasons. option wraps a type in a class, which just means more work for the garbage collector -- and I want to avoid that.

In this case especially, I have multiple fields that are all Some under the same circumstances, but I don't want to put them in a tuple because, again, tuples are classes -- and puts additional stress on the GC. So I end up accessing field.Value -- which defeats the purpose of option.

So unless there's an optimization I don't know about that causes option types to be treated as references that are potentially null, I want to just use null. Is there a way that I can do that?

Edit: To expand on what I'm doing, I'm making a bounding volume hierarchy, which is really a binary tree with data only at the leaf nodes. I'm implementing it as a class rather than as a discriminated union because keeping the items immutable isn't an option for performance reasons, and discriminated unions can't have mutable members, only refs -- again, adding to GC pressure.

As silly as it is in a functional language, I may just end up doing each node type as an inheritance of a Node parent type. Downcasting isn't exactly the fastest operation, but as far as XNA and WP7 are concerned, almost anything is better than angering the GC.


Solution

  • According to this MSDN documentation, if you decorate your type with the [<AllowNullLiteral>] attribute, you can then call Unchecked.defaultof<T>() to build a null for you.

    That seems to be the only way within F# to do what you want. Otherwise, you could marshall out to another .net language and get nulls from there... but I'm guessing that is not what you want at all