Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing let bound fields from static members
    primarykey
    data
    text
    <p>Is there any way to access let bound fields from a static member? The following gives the indicated error:</p> <pre><code>type Foo(x) = let x = x static member test() = let foo = Foo(System.DateTime.Now.Month) printfn "%A" foo.x //the field, constructor or member 'x' is not defined () </code></pre> <p>Whereas private explicit fields do allow access from static members:</p> <pre><code>type Bar = val private x:int new(x) = { x=x } static member test() = let Bar = Bar(System.DateTime.Now.Month) printfn "%A" Bar.x () </code></pre> <p>The documentation <a href="http://msdn.microsoft.com/en-us/library/dd469494.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/dd469494.aspx</a> states that "Explicit fields are not intended for routine use," yet accessing private instance fields from static members is certainly a routine scenario. Moreover, I don't believe you can set explicit fields within a primary constructor, which means if even one private instance field needs to be accessed from a static member, all of your fields must be moved over to explicit fields and you can no longer use a primary constructor -- it's all or nothing.</p> <p>As real world example where you would actually want to access a private instance field from a static member, consider a big integer implementation: a BigInteger class would be immutable, so the internal representation of the big integer would kept as a private instance field (let's call it <code>data</code>). Now, suppose you felt an <code>Add(other)</code> instance method was inappropriate for an immutable data structure and you only wanted to implement a static <code>Add(lhs,rhs)</code> method: in this case, you would need to be able to access <code>lhs.data</code> and <code>rhs.data</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload