Question

Is it legal for a record to have a nullable field such as:

type MyRec = { startDate : System.Nullable<DateTime>; }

This example does build in my project, but is this good practice if it is legal, and what problems if any does this introduce?

Was it helpful?

Solution

It is legal, but F# encourage using option types instead:

type MyRec = { startDate : option<DateTime>; }

By using option you can easily pattern match against options and other operations to transform option values as for example map values (by using Option.map), and abstractions such as the Maybe monad (by using Option.bind), whereas with nullable you can't since only value types can be made nullables.

You will notice most F# functions (such as List.choose) work with options instead of nullables. Some language features like optional parameters are interpreted as the F# option type.

However in some cases, when you need to interact with C# you may want to use Nullable.

When usign Linq to query a DB you may consider using the Linq.Nullable Module and the Nullable operators

OTHER TIPS

F# does not allow types that are declared in F# to be null. However, if you're using types that are not defined in F#, you are still allowed to use null. This is why your code is still legal. This is needed for inter-operability, because you may need to pass null to a .NET library or accept it as a result.

But I would say it is not a good practice unless your need is specifically of inter-operability. As others pointed out, you can use the option feature. However, this doesn't create an optional record field whose value you don't need to specify when creating it. To create a value of the record type, you still need to provide the value of the optional field.

Also, you can mark a type with the AllowNullLiteral attribute, and F# compiler would allow null as a value for that specific type, even if it is a type declared in F#. But AllowNullLiteral can't be applied to record types.

Oh and I almost forgot to mention: option types are NOT compatible with nullable types. Something that I kind of naively expected to just work (stupid me!). See this nice SO discussion for details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top