Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a record have a nullable field?

Tags:

f#

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?

like image 880
user1206480 Avatar asked Dec 14 '22 23:12

user1206480


1 Answers

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

like image 124
Gus Avatar answered Jan 09 '23 17:01

Gus