Pages

Friday, June 1, 2012

F# function parameters

From the google search, it is easy to find how to handle C#'s out/ref parameter in F#. This post tries to summarize the out/ref parameter between F# and C#. Both from C# to F# and F# to C#.
  • F# invoke C#
the C# code defines the following method inside ConsoleApplication1.Program class.
        public void OutTo9(out int i)
        {
            i = 9;
        }

        public int OutTo8(out int i)
        {
            i = 8;
            return 1;
        }

        public void RefTo10(ref int i)
        {
            i = 10;
        }

the F# needs to invoke the above function like:

        let a = ConsoleApplication1.Program()
        let b = a.OutTo9()
        let (returnValue, outValue) = a.OutTo8()
        let c = ref 0;
        a.RefTo10(c)
  • C# invoke F#
We define the F# code like:

//please remove extra space around < and > if the code does not compile. The blog does not support the character.

type MyClass() = class
    member public this.OutTo8([< System.Runtime.InteropServices.Out >]outValue:byref) = 
        outValue < - 8
    member public this.RefTo4(args:byref< int >) = 
        args < - 4
end

In the C# code, you can see:

            var a = new MyClass();
            int b = 0;
            a.OutTo8(out b);
            Console.WriteLine(b);
            a.RefTo4(ref b);


No comments: