4

This SO question is similar, but I do not see the answer which would satisfy me.

So, how does the equivalent of public static readonly string Name = ...; look in F#?

I can define static member Name = ..., but this creates static readonly property.

Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137

1 Answers1

5

I do not think there is a way to get a public static readonly field in F#.

If you use static let, you end up with a private field (and, in fact, I think this is actually compiled as a private field with a private static property Xyz):

type B() = 
  static let Xyz = 1

You can define actual fields with val, but this does not support initialization (so you need to set it in a static constructor) and the compiler requires such fields to be private:

type A() = 
  static do A.Xyz <- 1
  [<DefaultValue>] 
  static val mutable private Xyz : int 

If you try to make the field public, you will get:

error FS0881: Static 'val' fields in types must be mutable, private and marked with the '[]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type.

I think the error message gives an answer to your question. That said, I cannot think of a good reason why you would need a static public field - a let binding in a module should typically cover the use cases that you might have for a static public field (unless you need this because some library looks for static public fields via reflection...).

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Just curious, I am ok with `static member val`. I also see that F# adds additional check that static constructor successfully ran and value was initialized. – Pavel Voronin Mar 04 '20 at 23:28
  • 1
    @PavelVoronin Yep, I think the checks for succesfull initialization are exactly the reason why F# prevents normal public static fields... – Tomas Petricek Mar 05 '20 at 00:08
  • Btw, [here](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.missing.value?view=netcore-3.1) is an example =) – Pavel Voronin Mar 13 '20 at 15:35