F Sharp Classes - F Sharp (programming language)

What is F Sharp Classes?

Classes are the types that represent objects which have properties, methods, and events. ‘They are used for modelling actions, processes, and any other conceptual entities in applications’.


Syntax for defining a class type is as follows -


  • The type-name is any valid identifier. Default access modifier for this identifier is public.
  • The type-params describes about optional generic type parameters.
  • The parameter-list describes about constructor parameters. Default access modifier for this primary constructor is public.
  • The identifier used with the optional as keyword will give a name to the instance variable, or self-identifier, which can be used in the type definition to refer to the instance of the type.
  • The inherit keyword allows you in specifying the base class for a class.
  • The let bindings will allow you to declare fields or function values local to the class.
  • The do-bindings section includes the code which is to be executed upon object construction.
  • The member-list consists of additional constructors, instance and static method declarations, interface declarations, abstract bindings, and property and event declarations.
  • The keywords class and end which marks the start and end of the definition are optional.

Constructor of a Class

The constructor is code which creates an instance of the class type.

  • In F#, constructors work little differently than the other .Net languages. In the class definition, the arguments of the primary constructor are described as parameter-list.
  • The body of the constructor consists of the let and do bindings.

You can also add additional constructors by using the new keyword to add a member -

The below example illustrates the concept -


The below program creates a line class along with a constructor that calculates the length of the line while an object of the class is created -

On compiling and and executing the program, it produces the below result

Let Bindings

The let bindings in a class definition allow you to define both private fields and private functions for F# classes.

On compiling and and executing the program, it produces the below result

Please note the use of self-identifier gr for the Greetings class.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

F Sharp (programming language) Topics