How to declare an immutable struct with public fields?

According to this http://msdn.microsoft.com/en-us/library/vstudio/dd233233.aspx, that could be done as

type Vector2 =
   struct 
      val public X: int
      val public Y: int
      new(x: int, y: int) = { X = x; Y = y }
   end

If an F# Record would work for you, then this will work:

type MyInt = {
    Value: int
};;

Then to initialize:

let i = {Value=1};;

Since I'm not completely sure of your use case, I'm not sure how helpful this is.

EDIT: For what it's worth, if your reason for preferring a value type is that you want value type equality semantics, records support that (even though they are reference types). Consider this:

type Vector2 = {
     X:int;
     Y:int
};;

type Vector2 =
  {X: int;
   Y: int;}

let v = {X=1;Y=1};;

val v : Vector2 = {X = 1;
                   Y = 1;}

let v2 = {X=1;Y=1};;

val v2 : Vector2 = {X = 1;
                    Y = 1;}

v = v2;;
val it : bool = true

let v3 = {X=2;Y=2};;
v = v3;;
val it: bool = false

I mean to say that even though records are reference types, one of the reasons that people use value types (the equality semantics) is not a problem with records. Even though it's a reference type, I believe it's a lot closer to the behavior of the C# code you're trying to emulate--for what it's worth.

Tags:

F#