Thomas
Thomas

Reputation: 12117

how to use a C# nullable datetime in F#

I have a C# method that returns a DateTime?

and I would like to do the equivalent of:

DateTime? D;
if (D == null)
{
    ...
}
else
{
    Date = (DateTime)D;
    ...
}

but in F#

how can this be done?


I tried this:

    match (d: Nullable<DateTime>) with
    | None -> printfn "null"
    | NonNull s -> printfn "d %s" s.ToString

but it doesn't work; the "None" doesn't compile

Upvotes: 2

Views: 319

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243096

Fyodor's approach with converting Nullable to Option is safer as you then have to use pattern matching to access the value, but it should be noted that you can also use the methods of Nullable directly:

let nd = csharpMethod()
if nd.HasValue then printfn "Date = %A" nd.Value
else printfn "Null date"

This might be better in a tight loop where you want to avoid extra allocation.

Upvotes: 7

Fyodor Soikin
Fyodor Soikin

Reputation: 80765

First convert your value to Option via Option.ofNullable, then match on the result of that:

let nd = csharpMethod()
match Option.ofNullable nd with
| Some d -> printfn "Date = %A" d
| None -> printfn "Null date"

Upvotes: 7

Related Questions