The next type we will examine is a class, which is one of the most commonly used containers in the object oriented world. Like records, classes (and structs) provide all the features previously examined, such as methods, properties, indexers, interfaces, events, etc. The one thing that stands out the most is how a class is constructed in F#. This can be done either using explicit or implicit constructor notation.
Explicit Constructor Notation
This is actually the conventional way to create a class - define private variables, then expose public properties to access and modify the private variables in a safe way and all other interactions with the members of the class go through these properties. In C# you can simply define a class and it will compile with no problems, because a default constructor is automatically created for you even if you did not explicitly do it yourself. Therefore, you can new up an instance of the class and keep chugging away. In F#, you must define at least a default constructor for your class or it will not compile.
Take a look at the simple class definition in C#. If you look at the executable under ILDasm.exe you will see the constructor created for you.
In F#, this means you will have to take an extra step but follow the same process to create and use an object. For instance, if we asumed that a default constructor would be provided, an error is thrown by the compiler as shown in the code.
This is fixed by simply explicitly adding a constructor to initialize the necessary fields. The listing below shows the necessary code needed to get this to work. The downside to this approach is that it is a bit more verbose than we would like, given one of the cool functionality of F# is its compactness or succinctness.
Implicit Constructor Notation
We can move closer to the functional programming paradigm of compactness using implicit constructors. In general, we only need one constructor to initialize a class to a good state. To implement this form of constructors, basically put all the arguments needed for the construction of the class in good state in parenthesis following the name of the class, then adding the necessary public properties to access these fields/constructor arguments. I find this comparable to the notion of Automatic Properties introduced in C# 3.0. Here is what the new syntax would look like with this approach.
Another consequence of this approach is that you can use a series of let bindings before the member definitions to define the construction sequence of the class. This is just a trivial example but you can extend it to your own implementation.
Again, this type of approach provides only one constructor for use.