Consuming C# functions with out parameters from F#
June 4, 2017 1 Comment
C# has a number of functions with “out” parameters such as the various “TryParse” functions like Int32.TryParse. Functions with out parameters typically have a primary return value, like TryParse returns a boolean. The out parameters are also populated within the body of the function. We can call them secondary return values. Here’s an example of using Int32.TryParse:
int res; bool parseSuccess = Int32.TryParse("123", out res);
TryParse returns true if the string input was successfully parsed into an integer and “res” will be assigned that value. F# has no out values so how can we consume our functions from an F# program?
It turns out to be quite easy. The primary boolean and secondary integer return values are converted into a tuple:
let (parseSuccess, result) = Int32.TryParse("123"); printfn "Parse success: %b, result: %i" parseSuccess result
Note how the Int32.TryParse method was called without supplying the out parameter explicitly. We can therefore call an out function by only specifying the “normal”, i.e. non-out input parameters. Out parameters are turned into elements in a tuple. In the above case parseSuccess will be populated with the primary boolean return value of TryParse and result will get the value of the out parameter. If the conversion fails then parseSuccess is false and the out parameter will get its default value, i.e. 0 in this example.
Here’s the program output:
Parse success: true, result: 123
View all F# related articles here.
Pingback: F# Weekly #24, 2017 – Suave learning discount inside – Sergey Tihon's Blog