Consuming C# functions with out parameters from F#

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Consuming C# functions with out parameters from F#

  1. Pingback: F# Weekly #24, 2017 – Suave learning discount inside – Sergey Tihon's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: