views:

262

answers:

2

I have an F# variable defined as follows

let id = new Nullable<int>()

and I am passing it from F# into a C# function that takes a ref Nullable<int> and, subsequently, assigns it a value (it's basically stored procedure code auto-generated by Linq2Sql).

Unfortunately, when the function call exits, my id variable still has no value (i.e., is null). I've tried declaring it as mutable but F# complains that I cannot use mutable variables in closures.

Can someone help? Thanks!

A: 

I found this article which suggests a workaround.

Andrew Hare
+2  A: 

C#:

namespace TestLibrary
{
    public class TakesRefNullableInt
    {
        public void Foo(ref Nullable<int> ni)
        {
            ni = null;
        }
    }
}

F#:

// mutable version
let Main() =
    let mutable ni = new System.Nullable<int>(42)
    let tfni = new TestLibrary.TakesRefNullableInt()
    printfn "%A" ni
    tfni.Foo(&ni)
    printfn "%A" ni
Main()

// 'ref' version
let Main2() =
    let ni = ref(new System.Nullable<int>(42))
    let tfni = new TestLibrary.TakesRefNullableInt()
    printfn "%A" !ni
    tfni.Foo(ni)
    printfn "%A" !ni
Main2()

(potentially see also http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!677.entry)

Brian