Search code examples
.netf#functional-programmingrecordencapsulation

What's the difference between `type private MyRecord = {...}` and `type MyRecord = private {...}`


What's the difference between

type private MyRecord =
    { id : int }

And

type MyRecord = private
    { id : int }

From what I read:

  • In the first case, the type is private and only accessible within the file.
  • In the second case, the type is public but all fields are made private. We can expose the important ones through properties.

Solution

  • As the comment indicates, you've got it pretty much nailed. Interestingly, this fact isn't mentioned explicitly in the F# Language Specification, but could be inferred from the error which will be produced when trying to make a record field private, e.g. type MyRecord = { private id : int }

    Accessibility modifiers are not permitted on record fields. Use 'type R = internal ...' or 'type R = private ...' to give an accessibility to the whole representation.

    In effect, if you make "the whole representation" private, you cannot construct a record and also not access its fields outside the scope of the accessibility modifier.