mattgately
mattgately

Reputation: 1032

in f#, bind to a value from a c# library

I have a F# DLL and a C# DLL.

The C# library has a namespace Library with a class Toolbox that contains a member FUND_BITS like so:

namespace Library {
    public static class Toolbox {
        public static uint FUND_BITS = 0;
    }
}

and then in the F# library I have a binding:

let bf = Library.Toolbox.FUND_BITS

Now, I use bf in several functions defined in the library. When I change the value of FUND_BITS, I would expect that all of the F# functions would then use the updated value because I've binded bf to refer to Library.Toolbox.FUND_BITS, and have not declared it to be a mutable copy or anything. However, I have found that the functions use a stale value of FUND_BITS rather than the updated value.

Am I misunderstanding how F# creates immutable bindings to values? If so, I have not been able to find a way to bind in a manner that will update with changes, for instance:

let bf = &Library.Toolbox.FUND_BITS

Upvotes: 0

Views: 140

Answers (1)

phoog
phoog

Reputation: 43046

Unfortunately, "bind" in this case isn't the same thing as "bind" in the user-interface data binding sense. The line let bf = Library.Toolbox.FUND_BITS is basically a simple assignment statement. You'll find that type inference shows that the value bf is an instance of uint32.

If you want to read the value dynamically, you'd need to use a function that reads the value of the static variable each time it is invoked.

let bf = (function () -> Library.Toolbox.FUND_BITS)

EDIT This more concise version is due to Guvante

let bf() = Library.Toobox.FUND_BITS

In this case, bf will have a type of unit -> uint32.

If you want a two-way link between the values, then you could declare a property getter and setter that use the static field as a backing store, but that just scares me. A better approach would be just to reference the field directly whenever you need to read from it or write to it.

Upvotes: 5

Related Questions