Namespaces in F#

The main purpose of namespaces in F# is to group related types in one container and avoid name clashes of types. Namespaces are declared using the “namespace” keyword like in many other popular languages. A significant difference between C#/Java and F# is that F# namespaces can only contain type declarations. They cannot hold any values, i.e. anything that’s declared using the “let” keyword. They are only containers for types, i.e. elements that are declared using the “type” keyword.

A single F# source file (.fs) can contain multiple namespaces. A namespace starts with the namespace declaration and ends either at the end of the source file or at the next namespace declaration. Here’s an example with two namespaces where each namespace has a single type:


type Book = {
    title: string;
    author: string
with member this.takesLongTimeToRead = this.numberOfPages > 500


type Address = {
    street: string;
    city: string;
    number: int;

If we try to add a value in a namespace then we’ll get a compiler error:


let f = printf "Hello"

Namespaces cannot contain values. Consider using a module to hold your value declarations.

It’s of course possible to use types from different namespaces. The F# equivalent of a using/import statement is “open”:



type Order (product:string, value: int, address:Address) =
    member this.Product = product
    member this.Value = value
    member this.Address = address

Here’s an example of building a Book type and printing its title and whether it takes a long time to read from the Main entry point:

namespace com.mycompany.entry

open System

module Main =    
    let main args =    
        let myBook = {title = "F# for beginners"; numberOfPages = 600; author = "John Smith"}        
        let longTimeOrNot = myBook.takesLongTimeToRead
        printfn "Book title: %s, takes long to read: %b" myBook.title longTimeOrNot
        let keepConsoleWindowOpen = Console.ReadKey()

The ‘keepConsoleWindowOpen” value is only there to keep the console window open so that we can see the output. Here’s the output:

Book title: F# for beginners, takes long to read: true

View all F# related articles here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: