f-sharp
  1. f-sharp-access-control

F# Access Control

Access control is an important aspect of any programming language as it provides security to the program from unauthorized access to confidential data. F# provides different access control mechanisms to restrict the accessibility of certain members of a module or class.

Syntax

F# provides three access modifiers:

  1. public: This modifier allows a member to be accessed from anywhere in the program.
  2. private: This modifier restricts a member's accessibility to within the defining type only.
  3. internal: This modifier allows a member to be accessed from within the same assembly.
type Student =
    member val rollno = 0 with get, set
    member val name = "" with get, set
    member private this.Age = 18
    member internal this.Marks = 90

Example

type Student =
    member val rollno = 0 with get, set
    member val name = "" with get, set
    member private this.Age = 18
    member internal this.Marks = 90

let student1 = Student()
student1.rollno <- 1
student1.name <- "John"
// Accessing member with private modifier
printfn "Age is %i" student1.Age // Error: This field is not accessible from this code location.
// Accessing member with internal modifier
printfn "Marks obtained = %i" student1.Marks

Output

Age is 18
Error: This field is not accessible from this code location.
Marks obtained = 90

Explanation

In the above example, we have defined a Student class with four members. The rollno and name members are publicly accessible, whereas Age and Marks have private and internal access modifiers, respectively.

In the main method, we have created an instance of the Student class and set its rollno and name. However, when we try to access the Age member, the program generates an error because the member is private. Finally, we access the Marks member, which has an internal access modifier, and it is accessible within the same assembly, hence it prints the expected output.

Use

Access control is used to restrict the accessibility of members in F#. By implementing access modifiers, we can hide the implementation details of a module or class from outsiders to improve program security.

Important Points

  • Access control restricts the accessibility of members in F#.
  • F# provides three access modifiers: public, private, and internal.
  • Public members can be accessed from anywhere in the program.
  • Private members can be accessed within their defining type only.
  • Internal members can be accessed within the same assembly.

Summary

Access control is an essential feature that every programming language provides to secure a program's implementation details and access to confidential data. F# provides three access modifiers - public, private, and internal - that control the accessibility of members. By understanding these access modifiers, developers can design better and secure programs.

Published on: