2

Is it possible to create a simple public mutable field in F#? I'm creating a library that I will be accessing from a C# program and I need to be able to set a field from C#.

//C# Equivalent 
public class MyObj
{
    public int myVariable;
}

//F#
type MyObj = 
    //my variable here

    member SomeMethod() = 
        myVariable <- 10

//C# Usage
MyObj obj = new MyObj();
obj.myVariable = 5;
obj.SomeMethod()
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
user-8564775
  • 483
  • 2
  • 5
  • 15
  • Is for your library it necessary to expose this as a field or would a property also be fine? An automatically implemented property is a one liner in F# as well. I think the main two differences are that you could potentially have side-effects in properties (not something your code seems to indicate) and that a field can be as an out/ref argument. – Bram Jul 10 '14 at 15:39

2 Answers2

4
type MyObj() = 
    [<DefaultValue>]
    val mutable myVariable : int
    member this.SomeMethod() = 
        this.myVariable <- 10

You can leave off [<DefaultValue>] if there's no primary constructor, but this handles the more common case.

Daniel
  • 47,404
  • 11
  • 101
  • 179
2

How about:

[<CLIMutable>]
type MyObj = 
    { mutable myVariable : int }
    member x.SomeMethod() = 
        x.myVariable <- x.myVariable + 10

Then you can do:

var obj = new MyObj();
obj.myVariable = 5;
obj.SomeMethod();

or

var obj = new MyObj(5);
obj.SomeMethod();
ebb
  • 9,297
  • 18
  • 72
  • 123
  • By decoration with `CLIMutableAttribute`, you are compiling a F# record type which has no constructor as a Plain-Old CLR Object, with default constructor and property getters and setters, instead. – kaefer Jul 10 '14 at 20:37