Reading — step 1 of 5
Learn
F# runs on .NET. You will consume C# libraries — and they're class-based. F# has full OOP support: classes, interfaces, inheritance, properties.
Defining a class:
type Person(name: string, age: int) =
// primary constructor — name and age are bound from the argument list
member _.Name = name
member _.Age = age
member this.Greet() = sprintf "Hi, I'm %s" this.Name
let p = Person("Ada", 30)
p.Greet() // "Hi, I'm Ada"
printfn "%d" p.Age
Note the primary constructor: arguments come right after the type name. The body of the type can reference them.
Mutable properties:
type Counter() =
let mutable count = 0
member _.Count = count
member _.Increment() = count <- count + 1
Implementing an interface:
type Logger() =
interface System.IDisposable with
member _.Dispose() = printfn "closing"
// Use:
use logger = new Logger() // Dispose called automatically
Inheritance — less common in F# but supported:
type Animal(name: string) =
member _.Name = name
abstract member Sound : unit -> string
default _.Sound () = "..."
type Dog(name) =
inherit Animal(name)
override _.Sound () = "woof"
Calling .NET libraries:
open System.Net.Http
open System.IO
let client = new HttpClient()
let response = client.GetStringAsync("https://example.com").Result
File.WriteAllText("out.txt", response)
All of .NET — System.Collections.Generic.Dictionary, System.Linq.Enumerable, etc. — is available. Use F# idioms first, but reach for .NET when needed.
Exposing F# to C#:
- F# records become classes with auto-properties from C#'s perspective
- F# DUs become tagged classes (less ergonomic from C#)
- F# functions become static methods if module-level, or delegates if first-class
- For library code consumed by C#, prefer classes + interfaces over DUs
When to reach for OOP in F#:
- Implementing a .NET interface required by a library
- Mutable state with encapsulation (
Counter,StringBuilderwrappers) - F# library targeted at C# consumers
- Subtyping for polymorphism (rare but legitimate)
For most domain code, stick with records + DUs + modules of functions. OOP is the escape hatch for .NET interop, not the default.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…