What is the best way to do extensive null checks in F # when calling C # code

I would like to know how best to interact with C # code from F # in a functional way when I need to repeatedly check for null.

From C #, it’s easy because I have a null operator

public bool Authorize(DashboardContext dashboardContext)
{
    var context = new OwinContext(dashboardContext.GetOwinEnvironment());
    var user = context.Authentication.User;
    return user?.Identity?.IsAuthenticated ?? false;
}

From F # I made it

let authorize (ctx:DashboardContext) =
    match OwinContext(ctx.GetOwinEnvironment()) with
    | null -> false
    | c -> match c.Authentication.User with
            | null -> false
            | user -> user.Identity.IsAuthenticated

But I am not happy with that. What is the functional way to do this? I thought maybe some expression of the calculation would help, but I still don't know how to do it.

+6
source share
1 answer

Option.ofObj Option. , Option. , , , Option.bind.

let authorize (ctx:DashboardContext) =
    ctx.GetOwinEnvironment() |> OwinContext |> Option.ofObj
    |> Option.bind (fun c -> c.Authentication.User |> Option.ofObj)
    |> Option.map  (fun user -> user.Identity.IsAuthenticated)
    |> Option.defaultValue false

Option.bind Option<'a> , 'a Option<'a>. , "" a Some None.

, , , , , , , . Option.bind , .

, F # Authentication Identity . #, . F #, , , .

. . MaybeBuilder .

+9

All Articles