How to call methods with byref parameters from F#

When consuming C# libraries in F# projects, out parameters will be interpreted in F# with type byref. For example:

    public class Arithmetic
    {
        public static void sumAndDifference(
            int a, int b, out int sum, out int difference)
        {
            sum = a + b;
            difference = a - b;
        }
    }

Here, sumAndDifference has the following signature when the library is referenced from an F# project:
ByRef
The literal way to call the method is as follows, declaring reference value up-front and de-referencing them for use after the method call:

    let sum : int ref = ref 1
    let difference : int ref = ref 2
    Arithmetic.sumAndDifference(5, 3, sum, difference )
    printfn "Sum = %d, Difference = %d" !sum !difference

But F# also provides a much more concise syntax, allowing the out parameters to appear on the left hand side of an assignment:

    let sum, difference = Arithmetic.sumAndDifference(5, 3)
    printfn "Sum = %d, Difference = %d" sum difference

This syntax is so much cleaner and avoids any mention of references.

1 Comment

Filed under F#, Programming

One response to “How to call methods with byref parameters from F#

  1. Pingback: How to extend F# discriminated unions for use from C# | musingstudio

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 )

Google+ photo

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

Connecting to %s