As a part of rewriting my C# code in F# I have come across the situation where I do not know how to best handle the default values of the System.String type returned from a C# service.
The C# equivalent of what I would like to do would be:
var myCSharpString = CSharpService.GetCSharpString() ?? "";
Simply put, if the string returned by GetCSharpString is null or default(string), I would like it to be set to " " instead.
However, what will happen if I try to do the following statement in F#?
let myFSharpString = CSharpService.GetCSharpString
In the case where GetCSharpString returns null or default(string), will myFSharpString be the default value of strings in F# (that is: " ")? Or will I have to explicitly do a null check, such as:
let myFSharpString =
match CSharpService.GetCSharpString with
| val when val = Unchecked.defaultof<System.String> -> ""
| val -> val
I have found myself to do checks such as this several times, and I simply cannot get over the fact of how much code is needed for such a simple task.
Could someone enlighten me of whether such null checks are actually needed in F# when dealing with C# services that returns System.String?
Update:
I am not asking about the ??-operator in the combination with the F#'s Option type, as has been answered before in this post. Rather I am asking about how to handle the C# null value of strings in an F# context.
Another seemingly possible answer I have tried, would be to make a custom operator, such as:
let inline (|??) (a: 'a Nullable) b = if a.HasValue then a.Value else b
This, however, gives a compile error, since F# interprets the return value of GetCSharpString as of type 'string', which in F# is NotNullable.