liveBook · Manning

Class

As explained in F# in Action: A Revised Edition of Get Programming with F#

A class is an object-oriented programming construct that defines the structure and behavior of instances.

F# supports classes and methods alongside its functional features. Classes normally contain methods and can serve as a practical bridge to object-oriented .NET code, while modules and functions remain the idiomatic functional tools. section 6.1.6 section 11.1.1

Use a class when you need to:

  • Create instances and call methods from existing C# or .NET libraries. section 11.1.1
  • Represent data shared by several methods through a lightweight constructor and class definition. section 15.2.1
  • Apply object-oriented composition, such as passing an interface implementation into a class. section 15.2.1

Consuming a C# class

After referencing a C# project, F# can construct and use its class directly: open CsCode let person = Person () printfn $"{person.Name} is {person.Age} years old!" F# also permits constructor-call syntax such as FileInfo path or new FileInfo(path); the former is presented as the more idiomatic form. section 11.1.1

Injecting behavior through an interface

A class can receive an IPrinter and delegate output to it. The same ATM logic can therefore print to the console, append to a file, or use another implementation without changing its customer-description method.

Table 6.1 Comparing functions and methods in F# (view table figure)

 

Method

Function

Normally lives in

Classes

Modules or other Functions

Static or instance level?

Both

Static only

Currying / Partial application

No

Yes

Overloading

Yes

No

Type Inference

Limited

Full

Optional arguments

Yes

No

Pipelines

Limited

Yes

Compare classes and methods with modules and functions across placement, instance use, currying, overloading, type inference, optional arguments, and pipelines. section 6.1.6

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains instances, constructors, methods, interfaces, and composition, while contrasting classes with functions without detailing class internals.
Examples
Demonstrates C# Person consumption, FileInfo construction, filesystem access, and an ATM using interchangeable printer implementations.
What you can do after
Builds F# applications that instantiate .NET classes, call methods, define classes, and inject interface implementations.
How it connects
Connects classes with methods, constructors, interfaces, modules, functions, functional programming, object-oriented programming, and .NET.

Also explained in

Compare how 21 books explain class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.