Overview
Similarities
Modules and namespaces allow you to:
Organize code into zones of related functionality
Avoid name collisions
Differences
.NET equivalent
namespace
static class
Type
Top-level
Top-level or local
Contains
Modules, Types
Idem + Values, Functions
Annotable
β No
β Yes
Scope: Namespaces > Files > Modules
Use a module or a namespace
Either qualify the elements individually
Or import everything with the
openkeywordplaced anywhere before the usage, at the top recommended
open Name.Spaceβ‘ Cβ―using Name.Spaceopen My.Moduleβ‘ Cβ―using static My.Module
Imports order
β οΈ Warning: the order of the imports is taken into account, from top to bottom.
This allows shadowing (see below).
As a result, reordering imports in an existing file may cause compilation to fail!
So, although it's advisable to have imports sorted alphabetically, this isn't always possible. It is therefore advisable to indicate this in the code by means of a comment.
Shadowing at import
Imports are done without name conflicts but need disambiguation:
Modules and static classes are merged β
Types and functions are shadowed β - Last-imported-wins mode: see example below - Import order matters
β Recommendation
Shadowing is more likely to happen with common names such as add in the previous example, or map, filter... from the List, Seq... modules.
Qualification is recommended in this case, and it can be made mandatory by decorating the module with [<RequireQualifiedAccess>]π
Keyword global
globalBecause of Shadowing, we may come across cases where we can't import the right namespace. For example, having done open FsCheck and referenced the FsCheck.Xunit library, when you do open Xunit, we don't import the Xunit namespace from the Xunit library but the FsCheck.Xunit namespace!
π‘ We resolve fix issue by doing open global.Xunit.
Last updated
Was this helpful?