Correctly assigning C# default String to F# variable -


as part of rewriting c# code in f# have come across situation not know how best handle default values of system.string type returned c# service.

the c# equivalent of be:

var mycsharpstring = csharpservice.getcsharpstring() ?? ""; 

simply put, if string returned getcsharpstring null or default(string), set " " instead.

however, happen if try following statement in f#?

let myfsharpstring = csharpservice.getcsharpstring 

in case getcsharpstring returns null or default(string), myfsharpstring default value of strings in f# (that is: " ")? or have explicitly null check, such as:

let myfsharpstring =     match csharpservice.getcsharpstring     | val when val = unchecked.defaultof<system.string> -> ""     | val -> val 

i have found myself checks such several times, , cannot on fact of how code needed such simple task.

could enlighten me of whether such null checks needed in f# when dealing c# services returns system.string?

update:

i not asking ??-operator in combination f#'s option type, has been answered before in this post. rather asking how handle c# null value of strings in f# context.

another seemingly possible answer have tried, make custom operator, such as:

let inline (|??) (a: 'a nullable) b = if a.hasvalue a.value else b 

this, however, gives compile error, since f# interprets return value of getcsharpstring of type 'string', in f# notnullable.

define function , single-case active pattern:

let safestr = function     | null -> string.empty     | x -> x let (|safestr|) = safestr 

you can use either function:

let myfsharpstring = safestr <| csharpservice.getcsharpstring() 

... or active pattern:

let processcsharpstring (safestr x) =     // x never null :) 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -